YouTip LogoYouTip

Java Object Hashcode

# Java Object hashCode() Method [![Image 3: Java String Class](#)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 hash value of the object, which is an integer representing its position in a hash table. ### Example The following example demonstrates the use of the hashCode() method: ## Example class TutorialTest{public static void main(String[]args){// Object uses 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: 2255348171878246837929338653 The String and ArrayList classes use the hashCode() method. Both String and ArrayList inherit from Object, so they can directly use the hashCode() method: ## Example import java.util.ArrayList; class TutorialTest{public static void main(String[]args){// String uses hashCode()String str = new String(); System.out.println(str.hashCode()); // 0// ArrayList uses hashCode()ArrayListlist = new ArrayList(); System.out.println(list.hashCode()); // 1}} The output of the above program is: 01 The following example demonstrates that if two objects are equal, their hash values are also equal: ## Example class TutorialTest{public static void main(String[]args){// Object uses 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 values of obj1 and obj2 System.out.println(obj1.hashCode()); // 225534817 System.out.println(obj2.hashCode()); // 225534817}} The output of the above program is: true225534817225534817 * * Java Object Class](#)
← Css3 ImagesPython3 Att Time Clock β†’