Java Object hashCode() Method
The Object hashCode() method is used to obtain the hash value of an object.
Syntax
object.hashCode()
Parameters
- None.
Return Value
Returns the hash code of the object, which is an integer representing the position in the hash table.
Example
The following example demonstrates the use of the hashCode() method:
Example
class tutorialproTest {
public static void main(String[] args) {
// Object using hashCode()
Object obj1 = new Object();
System.out.println(obj1.hashCode());
Object obj2 = new Object();
System.out.println(obj2.hashCode());
Object obj3 = new Object();
System.out.println(obj3.hashCode());
}
}
The output of the above program is:
225534817
1878246837
929338653
The hashCode() method is also used by the String and ArrayList classes, which inherit from Object and can directly use the hashCode() method:
Example
import java.util.ArrayList;
class tutorialproTest {
public static void main(String[] args) {
// String using hashCode()
String str = new String();
System.out.println(str.hashCode()); // 0
// ArrayList using hashCode()
ArrayList<Integer> list = new ArrayList<>();
System.out.println(list.hashCode()); // 1
}
}
The output of the above program is:
0
1
The following example demonstrates that if two objects are equal, their hash codes are also equal:
Example
class tutorialproTest {
public static void main(String[] args) {
// Object using hashCode()
Object obj1 = new Object();
// Assign obj1 to obj2
Object obj2 = obj1;
// Check if the two objects are equal
System.out.println(obj1.equals(obj2)); // true
// Get the hash codes of obj1 and obj2
System.out.println(obj1.hashCode()); // 225534817
System.out.println(obj2.hashCode()); // 225534817
}
}
The output of the above program is:
true
225534817
225534817