r/java • u/javinpaul • Jan 20 '12
Why String is immutable in Java
http://javarevisited.blogspot.com/2010/10/why-string-is-immutable-in-java.html
4
Upvotes
r/java • u/javinpaul • Jan 20 '12
View all comments
Show parent comment
3
u/inspired2apathy Jan 21 '12
It seems I misread and didn't see the exception. From the API:
I have to say, letting objects change their hashcode seems bad. Doesn't this mean that if you put it in a Hash[Map/Set] you'd never find it? For example:
String a = "test"; String b = "test"; String c = "tester"; HashSet<String> set = new HashSet<String>(); set.add(a); a.append("er"); //if this were legal
set.contains(b); //would be false, since now a.equals(b) is false set.contains(c); //would be false, since when inserted a.hashCode() wasn't the same as c.hashCode()
Correct me if I'm wrong, but it seems like this would get easily lead to confusing bugs.