In Java, equals and hashcode have design requirements, equals equal, then hashcode must be equal, or vice versa. Why is there such a requirement? In the collection, such as HashSet, the object required to be placed can not be repeated, how to determine it? The hashcode is called first, and if the hashcode is equal, then the Equals is continued, and the equivalent is considered duplicates. If you override Equals, and if you do not override Hashcode, then Hashcode is inherited from object and returns memory encoding, which may appear equal to equals, and hashcode will not wait for the correct result when your object uses the collection.
Publicv put (K key, V value) {if(Key = =NULL) returnPutfornullkey (value); inthash =Hash (Key.hashcode ()); inti =indexfor (hash, table.length); for(entry<k,v> e = table[i]; E! =NULL; E =e.next) {Object k; if(E.hash = = Hash && (k = e.key) = = Key | |Key.equals (k))) {V OldValue=E.value; E.value=value; E.recordaccess ( This); returnOldValue; }} Modcount++; AddEntry (hash, key, value, I); return NULL; }
Java hashcode and equals