Skip to content
Advertisement

Hashcode value for Map Entry

As per javadocs hashcode for a map.entry is defined as :

int hashCode()
  Returns the hash code value for this map entry. The hash code of a map entry e is defined to be:
    (e.getKey()==null   ? 0 : e.getKey().hashCode()) ^
    (e.getValue()==null ? 0 : e.getValue().hashCode())

Plz confirm, if a bitwise XOR operator is used for calculating the hashcode value for a map entry?

Advertisement

Answer

Yes, it indeed is a bitwise XOR operator. I tried & got the same result for both the hashcode() method & by using ^ operator.

import java.util.*;
class TreeMapExample {
public static void main(String args[]) {
 // Creating TreeMap object
 TreeMap<String, Integer> tm = new TreeMap<String, Integer>();
 // Adding elements to the Map
 tm.put("Chaitanya", 27);
 tm.put("Raghu", 35);
 tm.put("Rajeev", 37);
 tm.put("Syed", 28);
 tm.put("Hugo", 32);

 // Getting a set of the entries
 Set set = tm.entrySet();
 // Get an iterator
 Iterator it = set.iterator();
 // Display elements
 int hash;
 while(it.hasNext()) {
    Map.Entry me = (Map.Entry)it.next();
    System.out.println("Key: "+me.getKey() + " & Value: "+me.getValue());
    System.out.println("hashcode value by method : "+me.hashCode());
    hash = me.getKey().hashCode() ^ me.getValue().hashCode();
    System.out.println("hashcode value by operator : "+me.hashCode()+"n");
 }
}
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement