4 ms·
Except newbie programmers should keep in mind that final is not simply synonymous with immutability. final ArrayList x = new ArrayList(); // x is final, so i
by mpobrien 17y ago
Except newbie programmers should keep in mind that final is not simply synonymous with immutability.
final ArrayList x = new ArrayList(); // x is final, so it can't be reassigned
x.add( "foo" ); // but we can still modify its contents
- city41 17y agoIt is synonymous with immutability though, in the strictest sense. In this case x and the ArrayList are two different things, one is final, the other is not. Yeah it's an anal distinction, but still a valid one.
- nradov 17y agoThe java.util.Collections class has several methods for making collection objects immutable. I use those whenever possible. Of course that only prevents changes to the collection, it doesn't prevent changes to individual collection elements. http://java.sun.com/javase/6/docs/api/java/util/Collections.html http://java.sun.com/javase/6/docs/api/java/util/Collections....
- lemming 17y agoIt's worth noting that this doesn't actually provide an immutable collection, it provides an immutable view of an existing one. If some other code has a reference to the underlying collection it can still be mutated. However this works well for the common case where you have a method which creates a local collection and returns the immutable view - in that case the collection is effectively immutable.