I am just grasping collections and found that the add() methods actually deep copy objects into the collections. Should they be called something like “copyInto” ?
import java.util.*;
class Test {
public static void main(String[] args) {
Set <Frog> setOfFrogs = new HashSet <Frog>();
Frog frog1 = new Frog("Kermit");
Frog frog2 = new Frog("Bob");
setOfFrogs.add(frog1);
setOfFrogs.add(frog2);
frog1.name = "May";
frog2.name = "Mary";
for (Frog eachFrog : setOfFrogs){
System.out.println(eachFrog.name);
}
}
}
This prints: “May” and “Mary”.
Sorry all it is a shallow copy. I need to get this “by reference” business into my thick head…
.add(..)simply adds the reference to the object in the collection. It does no deep copying. For example, if you change the object, the change will be reflected in the collection.