Why do I need to rewrite hashCode as well as equals
Each class has an equals method and a HashCode method. Because all classes inherit from the Object class. Public class Object {public Boolean equals(Object obj) {return (this == obj); } public native int hashCode(); } equals compares references to objects by default, using "==". The hashCode method is a native method that returns an integer. Both of these methods are not final, and they can be overridden. Classes like String, Math, Integer, Double, etc., are overridden with the equals() and hashCode() methods that determine whether two objects are equal. Object implements equals by default, but it obviously doesn't fit the needs of personalization, so it often needs to be overwritten. Public Boolean equals(Object anObject) {if (this == anObject) {return true; } if (anObject instanceof String) { String anotherString = (String)anObject; int n = value.length; if (n == anotherString.value.length) { char v1[] = value; char v2[] = anotherString.value; int i = 0; while (n-- ! = 0) { if (v1[i] ! = v2[i]) return false; i++; } return true; } } return false; } first compare by memory address, if the memory address is the same then it must be the same object. If the memory address is different then compare the contents of the char array, Public class Test01 {public static void main(String[] args) {String ff = new String("abcdef"); String dd =new String("abcdef") ; String ee = "abcdef"; System.out.println("dd memory address: "+ dd. HashCode ()); System.out.println("ff memory address: "+ ff.hashcode ()); System.out.println("ee memory address: "+ ee.hashCode()); System.out.println("dd memory address: "+ system.identityHashCode (dd)); Println ("ff: "+ system.identityHashCode (ff)); // Memory address system.out. println("ee memory address: "+ system.identityHashCode (ee)); // Memory address system.out. println(dd == ff); // == compares memory addresses, system.out.println (dd.equals(ff)); System.out.println(ee.equals(dd))); System.out.println(" Dd, ff, ee, etc., must be the same string, so hashcode must be the same, because hashcode is calculated based on the string contents "+". The equals method compares the memory addresses using ==, and if the memory addresses are different, compares the string values (contents). }} Output result: DD hashcode: -1424385949 FF Hashcode: -1424385949 EE hashcode: -1424385949 DD Memory address: 233530418 FF Memory address: 683287027 EE memory address: 1766822961 False true True Conclusion: The dd, ff, and EE objects have the same character strings, so hashCode must be the same, because hashCode is calculated based on the character strings. Memory addresses are not necessarily the same. Equals first compares memory addresses with ==, and then compares the values of strings if they are different.Copy the code
Reference: Why do I have to override the hashCode method when overriding equals