Java equals and hashcode Methods

Source: Internet
Author: User

1. First, equals and hashcode are independent of each other. It is based on performance to implement hashcode while implementing equals.

When inserting elements into the set, to ensure that each inserted element is different from the previously inserted element. How can we ensure the difference? Of course, the equals method is used. However, if there are already 1000 elements in the set and a new element is inserted, wouldn't the equals method be executed one by one for the new element and the existing 1000 elements, the efficiency is too low. At this time, the hashcode method takes effect. I will first execute the hashcode Method for inserting elements to generate a seat number, and then check whether someone has already sat down with this seat number, if no one is seated, it indicates that there is no currently inserted element in the set. You can insert it. If the seat is occupied, use the element to be inserted and the element equals, if they are the same, they are repeated elements and cannot be inserted. If they are different, you can use other methods to insert the elements to be inserted into a new seat. This method is much faster than the previous one-to-one comparison between the elements to be inserted and the existing 1000 elements. The combination of the equals method and hashcode greatly improves the search efficiency.

2. In addition to inserting elements into the set, hashcode can work. When put (Key, value) in the map, the key judgment is based on the same method.

3. for X. Equals (Y), hashcode (x) = hashcode (Y), but vice versa. For example, the hashcode of string AA and string BB is 2112.


The hashcode and equals descriptions in Java APIs are attached.

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.