HashCode returns an int hash value used by hash-based collections (HashMap, HashSet, etc.) to store and retrieve objects efficiently.
String s = "hello";
int hash = s.hashCode(); // hash value
Relationship with equals
If two objects are .equals(), they must have the same hashCode()
But two objects with same hashCode() may not be .equals()
if (a.equals(b)) {
a.hashCode() == b.hashCode(); // must be true
}
Example
public class Person {
String name;
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceOf Person)) return false;
Person p = (Person) obj;
return this.name.equals(p.name);
}
@Override
public int hashCode() {
return Objects.hash(name); // consistent with equals()
}
}
Tip
When working with HashMap or set - always keep in mind the
equals()
+hashCode()
contract.
Parent: _Object Methods