Java Object hashCode() Method

Java String类Java Object Class


The Object hashCode() method is used to get the hash value of an object.

Syntax

object.hashCode()

Parameters

  • None 。

Return Value

Returns the object's hash value, which is an integer representing the position in the hash table.

Example

The following example demonstrates the use of the hashCode() method:

Example

class ExampleTest { 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 String and ArrayList classes use the hashCode() method. Since both String and ArrayList classes inherit Object, they can directly use the hashCode() method:

Example

import java.util.ArrayList; class ExampleTest { 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, then their hash values are also equal:

Example

class ExampleTest { public static void main(String[] args) { //Object using hashCode() Object obj1 = new Object(); //Assign obj1 to obj2 Object obj2 = obj1; //Determine whether the two objects are equal System.out.println(obj1.equals(obj2)); // true //Get the hash values 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

Java String类Java Object Class

Other Extensions