Abhishek Raj
Abhishek Raj

Reputation: 99

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?

Upvotes: 0

Views: 998

Answers (4)

Abhishek Raj
Abhishek Raj

Reputation: 99

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");
 }
}
}

Upvotes: 0

WJS
WJS

Reputation: 40024

Here is the actual code taken from the Map.Entry as defined in the HashMap implementation. The ^ operator is the exclusive OR operator for Java.

public final int hashCode() {
       return Objects.hashCode(key) ^ Objects.hashCode(value);
}

However, the method of computation or specific result should be of no consequence to the user as long as the contract for hashCode is satisfied.

Upvotes: 1

Kirit
Kirit

Reputation: 295

Yes, hashCode() for Map.Entry returns the bitwise XOR of the hashCodes of the key and value.

Incorrect explanation - left in place for context so comments below make sense

This ensures that two instances of a Map.Entry object which have the same hashCode() value are guaranteed to have equal Key and Value properties. (Assuming the hashCode() method is properly overridden in both the Types used as Key and Value)

Upvotes: 0

rzwitserloot
rzwitserloot

Reputation: 102775

Yes, ^ means 'XOR'. Here is a list of all operators.

This sure seems like something a web search would have found a lot faster than asking an SO question.

Upvotes: 1

Related Questions