I am studying String
in java and while studying I came to know that hash code is generated for every string.
I want to know how hash code is generated in the case of StringBuffer
.
The StringBuffer
class does not override the hashCode()
method inherited from Object
class, whenever the hashCode
is invoked on a StringBuffer
instance the Object
class's implementation of hashCode
is used.
This is because the StringBuffer
is a mutable object unlike the String
you can easily modify the state of the StringBuffer
object after its creation. This makes it unsuitable for use in any "hash" based data structures like a HashMap
as the it will be inconsistent.
The hashCode
method of the Object
class is a native method which is typically implemented by converting the internal address of the object into an integer as the hash code value or may not as it depends on the internal implementation of the JVM, but in the immutable String
class the hashCode
is overriden and implemented using the content of the String
object to make it consistent for use in hash data structures.
Just as simple experiment you can run the snippet to check this theory:
StringBuffer s1 = new StringBuffer("foo");
StringBuffer s2 = new StringBuffer("foo");
System.out.println(s1.hashCode() == s2.hashCode());
System.out.println(s1.toString().hashCode() == s2.toString().hashCode());
This will output false
and true
. This is because the String
instance is actually using the state of the object to calculate the hash code, so it is same for both s1.toString()
and s2.toString()
.