3

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.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Jasmeet Singh
  • 133
  • 1
  • 5
  • 1
    A question like this is something you should consider reading [the documentation](https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/lang/StringBuffer.html) for rather than asking here. – Mihir Kekkar Aug 31 '19 at 06:11

2 Answers2

2

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().

Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44
  • @JasmeetSingh you're welcome. – Fullstack Guy Aug 31 '19 at 06:44
  • 1
    Sorry, but this answer is factually incorrect. In modern JVMs, the machine address is typically NOT used to generate the identity hashcode. See the linked Q&A. – Stephen C Aug 31 '19 at 07:59
  • @StephenC I used the reference form the Java docs, which it seems does not go into the implementation technique, thanks for the link I will update the answer. – Fullstack Guy Aug 31 '19 at 08:31
1

StringBuffer extends Object class directly and it does not override hashCode from Object class. So the implementation of StringBuffer::hashCode is the same as for Object::hashCode.

Michał Krzywański
  • 15,659
  • 4
  • 36
  • 63