Small example of the hashCode method in Java

  • 2020-04-01 02:38:39
  • OfStack

In Java, there is a rule that two identical objects (equals equals to true) must have the same hash code. There is a hashCode method in the Object class that you can call to view the hash code for the Object. Here's an example.


package test;
public class Test {
 public static void main(String args[]){
  String str1 = "aaa";
  String str2 = str1;
  String str3 = "bbb";
  System.out.println(str1.equals(str2));
  System.out.println("str1.hashCode():"+str1.hashCode());
  System.out.println("str2.hashCode():"+str2.hashCode());
  System.out.println("str3.hashCode():"+str3.hashCode());
 }
}

The running result of the above example is


true
str1.hashCode():96321
str2.hashCode():96321
str3.hashCode():97314

As you can see, str1 and str2 are equal to true, and their hash code is the same.


Related articles: