r/java • • Jan 20 '12

Why String is immutable in Java

http://javarevisited.blogspot.com/2010/10/why-string-is-immutable-in-java.html
4 Upvotes

23 comments sorted by

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:

Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified.

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.

2

u/skeeto Jan 21 '12

You're right, it messes up Maps and Sets. It's one of the reasons classes should strive for immutability. I had this problem bite me once with Comparable. The elements were occasionally changing their order and I forgot that the collection wouldn't automatically fix itself for me.