Java System identityHashCode() Method
Example
Compare the hash codes of two strings with the same text:
public class Main {
public static void main(String[] args) {
String a = new String("Hello");
String b = new String("Hello");
System.out.println(a.hashCode());
System.out.println(b.hashCode());
System.out.println(System.identityHashCode(a));
System.out.println(System.identityHashCode(b));
}
}
Note: The output is different each time you run the program.
Definition and Usage
The identityHashCode() method returns the default hash code of an object (a number that Java uses to tell objects apart, for example in a HashMap). It is the number that the hashCode() method of the Object class returns, even if the class of the object has its own hashCode() method.
In the example, both strings have the same hashCode(), because the String class calculates it from the text. But they are two different objects, so their identity hash codes are different.
Syntax
public static int identityHashCode(Object x)
Parameter Values
| Parameter | Description |
|---|---|
| x | Required. The object to get the hash code for. |
Technical Details
| Returns: | An int value, the default hash code of the object, or 0 if the object is null. |
|---|
Related Pages
❮ System Methods