HashMap hm = new HashMap();
StringBuilder sb = new StringBuilder("test");
hm.put(sb, "second");
// above code gets hacode for sb and places it corresponding bucket
sb.append("123");// with appending of "123", sb hascode will change
System.out.println("element is is" + hm.get(sb));// print "second"
Now hm.get(sb) should search the key in the bucket as per new hashcode. so it should not get any object under that bucket and should get null . So why its getting "second"?
The StringBuilder
class does not override hashCode
, so it inherits the hashCode
method from Object
. Therefore, the StringBuilder'
s contents do not affect the hash code, and even when you change its contents, the HashMap
is still able to find the StringBuilder
.
By default it looks like StringBuilder doesn't use its contents as part of its hashCode(), it just inherits the default hashCode() from Object which uses the memory address as its seed. So the memory address hasn't changed, thus the key still works.
If you wanted the behavior you expected, override the hashCode method to return
@Override
public int hashCode() {
return this.toString().hashCode();
}
and don't forget to override equals() as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With