1

If we do not override the hashCode(), how it calculate hashCode for custom object by default?
i.e.

class TrieNode {
    Character letter;
    TrieNode parent;
    Map<Character, TrieNode> children;
    boolean isEndOfWord;
    TrieNode(Character letter, TrieNode parent, boolean isEndOfWord) {
        this.letter = letter;
        this.parent = parent;
        this.isEndOfWord = isEndOfWord;
        children = new HashMap<Character, TrieNode>();
    }
}

Usage:

Set<TrieNode> set = new HashSet<TrieNode>();
TrieNode trieNode = new TrieNode('c', parentNode, true);
set.add(trieNode);


Note:
  • If we do not override the "hashCode()".

Clarify Question:

  • By default, how this HashSet calculate the hashCode for this custom object?
  • Where to find it in the Java doc?

Addition:
I have tried to find it in the Java doc, but did not get it.
I have tried to find these places:

  • HashSet.class
  • AbstractSet.class
  • Object.class
  • System.class
Zhaonan
  • 939
  • 1
  • 11
  • 20

2 Answers2

2

If we do not override the hashCode(), how it calculate hashCode for custom object by default?

It uses the hashCode() method from Object. Essentially it is a reference address. The Javadoc says,

As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • Hi @ElliotFrisch, when I checked the "AbstractSet.class", it invoke the Object's hashCode() to calculate the hash code, and then I checked the object.hashCode(). I found the Object.class does nod implement it, and then I have no idea where is the next hint...... From your saying"but this implementation technique is not required by the JavaTM programming language", does that mean, there is definitely no implementation in java for hashCode(), maybe that just is implemented by other organization? – Zhaonan Aug 11 '14 at 17:23
  • I provided the Javadoc link in my answer. It is in `java.lang.Object#hashCode()` – Elliott Frisch Aug 11 '14 at 17:24
2

All classes extend Object class which has the hashcode() method.It usually returns a distinct value as it converts the internal address of an Object,but it is not necessarily required

Kumar Abhinav
  • 6,565
  • 2
  • 24
  • 35
  • Thanks @KumarAbhinav, I got it, seems that is "public static native int identityHashCode(Object x);" to calculate the address of object, but why can not find the implementation? That is not open-source? – Zhaonan Aug 11 '14 at 17:28
  • @Zhaonan hashcode documentation http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#hashCode() – Kumar Abhinav Aug 11 '14 at 17:33