HashCode and equals Methods

Source: Internet
Author: User

I have long had doubts about the hashCode and equals methods, and I have never been able to solve them. Today I remember Baidu, But I did write it in my own words, so it should be original.


Values in HashSet or HashMap cannot be repeated. Let's assume that there are already 1000 values in it,

Below I want to save 1,001st values. How can I determine whether these 1001 values are equal to the first 1000 values?


At this time, someone will say that the equals method is used. Yes, yes, but it is not very slow if you want to equals the 1000 values ?, 1000 is okay, so what if it is 10000 or 100000? This is not enough.


So hashCode is used as an address value. When you store data, you can directly find the physical memory corresponding to your hashCode to see if you have already stored a value. If you do not store it, You can store it directly. If you store it, call the equals method, if they are equal, they are discarded, and they are stored together with the form of a bulb.


Therefore, when you create a class and you want to rewrite the equals method, you 'd better also rewrite the hashCode. Otherwise, you have created two attributes and the methods are all equal, can insert HashSet or HashMap, which may be contrary to your original intention.


Another point is that the criteria for judging hashCode and equals should be the same. For example, you use equals to determine whether the two attributes in the object are equal to each other to determine whether the object is equal, the value returned by your hashCode method is also related to the two attributes.

Because your hashCode is used to prevent equals from judging the existence of so many times, there may be other in-depth functions)

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.