Friday 15 March 2013

clone - make deep copy in java -



clone - make deep copy in java -

given next 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 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(){ homecoming this.clone; } }

and output :

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

actually, want utilize cache store original list contains"one, 2 ,three". when stores list, , remove implemented 'original' list, not impact 1 stored in cache, means still contains "one,two,three". how it?

you storing reference list, result have expected!

instead, create re-create when build:

public void store(arraylist<string> original){ clone = new arraylist<string>(original); }

java clone

No comments:

Post a Comment