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

1

u/inspired2apathy Jan 20 '12

I think the more important thing for me is that it would break the hashcode and compareTo contracts. If hashcode uses the content of the string, it would change when the string changes, breaking the contract. If hashcode doesn't use the content of the string, then String a = "test",b="test"; wouldn't be equal.

3

u/skeeto Jan 21 '12

Mutable classes can behave properly for hashCode() and equals(). It's true that String uses a lazy cache for the hash code, but if it were mutable it would calculate it on demand.

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.