Search code examples
javahashmapjavadochashcodecustom-object

In Java HashSet, how it calculate hashCode for custom object?


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

Solution

  • 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.)