chrisTina
chrisTina

Reputation: 2368

make deep copy in java

Given the following codes:

ArrayList<String> original = new ArrayList<String>();
    original.add("one");
    original.add("two");
    original.add("three");

    Cache ch = new Cache();
    ch.store(original);

    original.remove(0);
    original.remove(0);
    System.out.println("modified list is"+original);
    System.out.println("cache list is"+ch.getCache());

and a Cache class:

public class Cache {
private ArrayList<String> clone = new ArrayList<String>();

public void store(ArrayList<String> original){
    this.clone = original;
}

public ArrayList<String> getCache(){
    return this.clone;
}

}

And the output is :

modified list is[three]
cache list is[three]

Actually, I want to use the cache to store the original list contains"one, two ,three". When it stores that list, and a remove is implemented with the 'original' list, it does not affect the one stored in the cache, means it still contains "one,two,three". So how to do it?

Upvotes: 1

Views: 88

Answers (3)

Ian2thedv
Ian2thedv

Reputation: 2701

In Cache you're declaring and initialising a new array list and then replacing it with the reference of original. Do this:

public void store(ArrayList<String> original)
    for(String element:original) {
        this.clone.add(element);
    }
}

Upvotes: 0

saikumarm
saikumarm

Reputation: 1575

Here IMHO, clone is actually referring to original therefore any changes that you make to original will reflect in clone object. In order to preserve the values in the original ArrayList in clone, one way is copy the contents of original via some logic instead of clone = original; // (which is referencing ).

Upvotes: 0

fge
fge

Reputation: 121712

You are storing only the reference to the list, so the result you have is expected!

Instead, make a copy when you build:

public void store(ArrayList<String> original){
    clone = new ArrayList<String>(original);
}

Upvotes: 3

Related Questions