The API doc says clone() in ArrayList creates a shallow copy ("the elements themselves are not copied"). I found that it DOES copy the values however: ArrayList al = new ArrayList(); String st1 = new String("st1"); ArrayList am = (ArrayList)al.clone(); System.out.println(am.size()); System.out.println(am.toString()); Output is 1 and "[st1]". Any ideas?
Joined: Nov 13, 2001
Sorry. I forgot to include the al.add(st1) in the code above. I had it in the sample program I ran. Not sure why the behavior appears to contradict the API doc. Thanks.
Irachi, your code does not prove what you are trying to prove. The clone method does create a shallow copy and not a deep one. In this code cloning the ArrayList returns a new reference to the ArrayList containing a reference to elements of the cloned ArrayList and not copies of those elements. Try looking at the result of al.get(0)==am.get(0) and you'll see that the reference of the elements contained in both lists are in fact the same. Moreover, we'd like you to read the JavaRanch Naming Policy and register again. Thank you for your cooperation HIH ------------------ Valentin Crettaz Sun Certified Programmer for Java 2 Platform [This message has been edited by Valentin Crettaz (edited November 26, 2001).]
If I understand your reply correctly, the am reference is a new reference to a new ArrayList (am==al returns false) but it contains the same references as the original ArrayList. So the "shallow" charateristic describes how the references are copied into the new ArrayList but not the objects those references point to. Correct? Isn't this really the result of the fact that the objects themselves never got stored in the original ArrayList, only the references to those objects? I guess I was looking at the references stored in the ArrayList as the ArrayList's "values" and wondered which they got copied. If the above bit is correct I think I understand now. Thanks!
Joined: Aug 26, 2001
You got it Irachi But please change your username so that it complies to out naming policy (see link above). Sorry for repeating myself. ------------------ Valentin Crettaz Sun Certified Programmer for Java 2 Platform