5

What is the Difference between Hash32 and Hash in String Object

While Debugging I have found the String Object displays hash=0 and hash32=0 as shown in below image.Some could please explain the reason it is displayed.

enter image description here

Thanks for the Reply

Java Beginner
  • 1,635
  • 11
  • 29
  • 51

1 Answers1

7

The performance advantages of HashMaps can be "negated" by feeding it carefully chosen keys, so that you get lots of collisions. This reduces the O(1) access/whatever time for a HashMap to O(n), significantly reducing performance.

hash32 is the cached value for an alternative hashing algorithm, used for Strings, so that if there were too many collisions with the default algorithm a different algorithm could be used to try to reduce the number of collisions. Source here:

Java SE 7u6 introduces an improved, alternative hash function...

The alternative hash function improves the performance of these map implementations when a large number of key hash collisions are encountered.

The alternative hash function is only applied to keys of type String.

HashMap was rewritten in Java 8 to use ad-hoc TreeMaps for Comparable keys if there were too many collisions for any particular bucket, meaning that performance went from O(1) to O(lg n) instead of O(1) to O(n) -- a significant improvement. As Strings implement Comparable, it was decided that the alternative hashing scheme was no longer needed, and it was removed.

Community
  • 1
  • 1
awksp
  • 11,764
  • 4
  • 37
  • 44