Reputation: 31
In Hashmap for null key the index is 0 but for Empty string what will be the index. I debug it and found that it is creating a linkedlist at the 0th index and storing both value there.
So why empty string value is storing in the 0th position and if it is calculating the index using the hashmap of the empty string then what will the hashcode of empty string.
HashMap<String, String> hm= new HashMap<>();
hm.put("", "");
hm.put(null, null);
Upvotes: 3
Views: 10818
Reputation: 14601
The hash code of the empty string will be 0
at least in the Oracle's Java 8 implementation.
This is an extract of the source of the `java.util.HashMap class in Java 1.8 of the method used to calculate the hash:
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
This is the relevant method which calculates the hash.
So in essence this is how it calculates the hash code of the empty string:
System.out.println(("".hashCode()) ^ ("".hashCode() >>> 16));
The hash code of null
will be 0
anyway. See the code above with the hash
method.
Upvotes: 3
Reputation: 1735
Because hashcode for an empty string returns 0, and that it is the same value for a null object. So you have a collision of hash, so it goes to the same cell.
* At least for the current implementation in the class String - that could change one day
Upvotes: 3
Reputation: 181735
Hash codes in Java have to meet the following requirement:
- Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
Note the last sentence. This allows for hash codes to be unpredictable between different runs of the same application, which protects against a certain class of denial of service attacks.
So there is no way to predict what the hash code of any particular object (be it null
or an actual object) will be. You only know that it'll be the same for the same object and for objects that are equal to it according to the equals
method.
Upvotes: -1