Posted By:
Robert_Lybarger
Posted On:
Tuesday, August 15, 2006 11:52 PM
I really thought it would be easier than this. It is somewhat late for me after a long day, so I probably just went down a blind alley, but this is *a* solution, though I really don't imagine its the *best* one. It sounds like you are looking for the "public Object clone()" method. Implement this in your Amit class to return a new Amit instance with the correct values copied over. Then, when creating "newAmits", just create an empty ArrayList, then loop through the original version, calling "clone()" on each one in turn and adding the result to your "newAmits" member. Here's how it looks, with your 'assertEquals' removed:
import java.util.ArrayList;
import java.util.List;
class Cloning {
public static void main(String[] args) {
new Cloning();
}
public Cloning() {
List amits = new ArrayList();
Amit amit = new Amit(5); amits.add(amit);
List moreAmits = new ArrayList();
for(Amit a : amits) {
moreAmits.add( (Amit)(a.clone()));
}
moreAmits.iterator().next().value = 10;
System.out.println("original amit value is: "+amit.value);
}
}
...and...
public class Amit implements Cloneable {
public Amit(int i) {
this.value = i;
}
public int value = 100;
public Object clone() {
Amit newAmit = new Amit(this.value);
return newAmit;
}
}
Pity I can't find (there doesn't seem to be?) a "copyAllElements" method in the standard collections classes to help abstract this... though you'd still need to write an implementation for your "clone" either way.