Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast making copy of an hash map [duplicate]

Possible Duplicate:
clone utility for HashMap in java

I have an one to one map as:

      HashMap<Integer, ArrayList<Double>> matrix;

Integer is index and ArrayList has dimnesion of about 50. Index may have size upto one million. I would like to make copy(including Arraylist value) of it as soon as possible.

I did following:

 public Map<Integer,ArrayList<Double>> getCloneOfMatrix(){
 Map<Integer, ArrayList<Double>> newMatrix = new HashMap<Integer,ArrayList<Double>>(); 
    for(int i=0 ; i < indexSize; i++){
        ArrayList<Double> arrList = new ArrayList<Double>();
        arrList=(ArrayList<Double>) matrix.get(i).clone();
        newMatrix.put(i,arrList);

    }           
    return   newMatrix;
}

I found it computationally expensive, is there any way to do it in faster way.

like image 290
thetna Avatar asked Jan 01 '26 01:01

thetna


1 Answers

The fastest way to do this is to avoid needing to make the copy in the first place.

If you use a copy on write approach, you can have two references to the same structure but neither will see the others changes. This avoids the need to copy everything and depending on your usage, avoids the need to copy anything.

like image 178
Peter Lawrey Avatar answered Jan 02 '26 14:01

Peter Lawrey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!