Determine if the elements in the set are duplicated, = =, equals, Hashcode method research-code Demo

Source: Internet
Author: User


Sitebean site1 =NewSitebean ("http://www.yjbys.com/", "" "); Sitebean Site2=NewSitebean ("http://www.yjbys.com/", "" "); Set<SiteBean> Aaset =NewHashset<>();        Aaset.add (SITE1);        Aaset.add (SITE2); System.out.println (Site1==site2);        System.out.println (Site1.equals (site2)); System.out.println (Site1.hashcode ()==Site2.hashcode ()); Sitebean Site3=NewSitebean ("Http://www.yjby1s.com/11", "" "); Sitebean Site4=NewSitebean ("Http://www.yjby1s.com/11", "" ");        Aaset.add (Site3); Aaset.add (site4);
Sitebean overrides the Hashcode and Equals methods with the following code://The comparison is the domain name@Override Public inthashcode () {returnSiteurl.hashcode (); }    //The comparison is the domain name@Override Public Booleanequals (Object obj) {if(obj = =NULL) {            return false; }        if(GetClass ()! =Obj.getclass ()) {            return false; }        FinalSitebean Sitebean =(Sitebean) obj; returnobjects.equals (SiteURL, Sitebean.siteurl); }

The output is as follows:

false true true
and the number of elements in set is 2.

The internal implementation of the set is actually a map, and the Hashcode method is called when the key of the map is processed, the code is as follows

Static Final int Hash (Object key) {        int  h;         return null) ? 0: (H = key.hashcode ()) ^ (h >>>);    }

After calling the Hashcode method method, the Equals method is called, so the element repeatability of set is judged by equals.

The following attempt does not override the Hashcode method:

Output:

false true false
and the number of elements in set is 4.

The following attempt does not override the Hashcode and Equals methods:

Output:

Falsefalse
and the number of elements in set is 4.

Ouyen Rights

Reprint Annotated: http://www.cnblogs.com/langtianya/p/4421582.html

Determine if the elements in the set are duplicated, = =, equals, Hashcode method research-code Demo

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.