Java hashcode and equals

Source: Internet
Author: User

When to use Hashcode, when to use equals?

First Java generates a default hashcode for each object, the Java core is the memory address of the Java object, but the Equals method compares the memory address of the object, which is not the way Java is designed. See a blog post, http://www.cnblogs.com/dolphin0520/p/3681042.html, Hashcode is a number related to the memory address of the object, Javacore This hashcode is the hash code of the returned object, which is an arbitrary integer, including positive and negative numbers.

So when to use Hashcode, when to use equals? Is the object stored in a structure such as set, map, which does not allow repeating elements, the object itself must override the Hashcode, Equals method, in order to guarantee that the inserted element is unique.

Hashcode is based on the value generated by the members of the object, as the index of the lookup, so that the lookup is very fast, the Equals method compares the value of the member variables of the object is equal, the double coverage mechanism to ensure that duplicate objects are not inserted, it is important to note that if you need to modify some members of the object, Then these members do not participate in the calculation of hashcode, otherwise will generate a different hashcode overwrite the original object, so that the object's reference will be invalidated (point to the object address or before the modification), the reference object of the Remove, contains method will be invalidated, This blog post will cause a memory leak (http://blog.csdn.net/shixing_11/article/details/5652935), the solution is not to let the modified variable participate in the hashcode calculation, This will allow you to delete and add the normal

Please refer to the blog post:

http://blog.csdn.net/veryitman/article/details/6894447 (short)

http://blog.csdn.net/afgasdg/article/details/6889383 (long, full)

Java hashcode and equals

Related Article

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.