Search code examples
javaclone

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?


Solution

  • 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);
    }