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