Java hashcode and equals

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.