Dark Horse programmers learn hashset experience

Source: Internet
Author: User

 

 

----------- Android training, Java training, and Java learning technology blog. We look forward to communicating with you! ------------

The hashset is an unordered set. an unordered set means that the order in which elements are put is different from the order obtained.

In addition, this set cannot store the same elements.

Now the problem arises. How does hashset determine whether two elements are the same?

Hashset is first judged by the hashcode () method of the element object,

The hashcode () method can be used to calculate a value and compare it with this value. If the value is the same, another method equals () will be called to compare it.

If the hashcode values of the two elements are the same, it determines whether the return value of the equals method is true. If it is true, the hashset considers it to be the same element and will not be saved in the set.

If the hashcode values of the two elements are different, the equals () method is not called. hashset considers that not the same element will be stored in a set.

 

As described above, we can also manually save an element as two elements into the hashset,

Override only requires the hashcode () method and equals () method. For example

Staticn int I = 1;

Public int hashcode ()

{I ++}

You only need to let the hashcode () method return different values or the equals () method return false

 

 

----------------------- Android training, Java training, Java learning technology blog, hope to communicate with you! ----------------------

 

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.