Java Hashtable # hashCode () implementation error?

I am wondering if the default implementation of Java Hashtable#hashCode() broken when the Hashtable contains only entries with the same keys and values ​​for each pair.

See, for example, the following appendix:

 public class HashtableHash { public static void main(final String[] args) { final Hashtable<String, String> ht = new Hashtable<String, String>(); final int h1 = ht.hashCode(); System.out.println(h1); // output is 0 ht.put("Test", "Test"); final int h2 = ht.hashCode(); System.out.println(h2); // output is 0 ?!? // Hashtable#hashCode() uses this algorithm to calculate hash code // of every element: // // h += e.key.hashCode() ^ e.value.hashCode() // // The result of XOR on identical hash codes is always 0 // (because all bits are equal) ht.put("Test2", "Hello world"); final int h3 = ht.hashCode(); System.out.println(h3); // output is some hash code } } 

The hash code for an empty Hashtable is 0. After the record with the key "Test" and the value "Test" been added to the Hastable, the hash code is still 0.

The problem is that in the Hashtable hashCode() method, the hash code of each record is computed and added to the hash code as follows

 h += e.key.hashCode() ^ e.value.hashCode() 

However, the XOR for identical hash codes (which is the case for identical strings) is always 0. Thus, records with identical keys and values ​​are not part of the Hashtable hash.

This implementation is broken because the Hashtable has actually changed. It doesn't matter if the key and value match.

+6
source share
3 answers

From the hashCode documentation;

It is not required that the two objects be unequal in equals (java.lang.Object), then calling the hashCode method on each of the two objects should produce different integer results. However, the programmer must be aware that integer results for unequal objects can improve the performance of Hashtables.

In other words, poor implementation is possible. Broken - not according to specification.

+6
source

He did not break, his work was designed and advertised. The hash code of two Map does not require two Map be equal.

+5
source

The only requirement for hashCode is that if two objects are equal, then their hash codes must be equal. Thus,

 public int hashCode() { return 123; } 

It works great, although it is not optimal.

+1
source

Source: https://habr.com/ru/post/911138/


All Articles