From this link
Name objects are immutable. All other things being equal, immutable types are the way to go, especially for objects that will be used as elements in Sets or as keys in Maps. These collections will break if you modify their elements or keys while they're in the collection. How do we know that the class "Name" is immutable? (class name visible in the link above mentioned)
What do they actually mean with "the collections will break if you modify their elements?"
Thanks in advance.
Because with mutable classes, you can change the properties based which they are organized/ordered in the Collections, and the holder class would not know about it.
Think that you could do:
public class Name implements Comparable<Name> {
private String firstname = null
// getters and setters
public int compareTo(Name name) {
// Compare based in firstName
}
}
And then:
Name name1 = new Name("John");
Name name2 = new Name("Mike");
SortedSet<Name> set = new TreeSet<Name>();
set.add(name1);
set.add(name2);
name1.setFirstName("Ralph");
Now, is set
ordered or is it not?
In a similar way, changes that affect the hashCode
of the instance break HashMap
and similars, because the first that does these classes when inserting/retrieving objects is to use a specific bucket
based in that value.