Java overrides the Equals method and the Hashcode method

Source: Internet
Author: User

PackageCom.ddy;

PublicclassUser {
PrivateInteger ID;

PrivateString name;

PrivateString address;

PrivateString phone;

PublicInteger GetId () {
returnId
}

PublicvoidSETID (Integer ID) {
This. id = ID;
}

PublicString GetName () {
returnName
}

PublicvoidSetName (String name) {
This. Name = Name = =NULL?NULL: Name.trim ();
}

PublicString getaddress () {
returnAddress
}

PublicvoidSetaddress (String address) {
This. Address = Address = =NULL?NULL: Address.trim ();
}

PublicString Getphone () {
returnPhone
}

PublicvoidSetphone (String phone) {
This. Phone = Phone = =NULL?NULL: Phone.trim ();
}

@Override
PublicintHashcode () {
FinalintPrime = 31;
intresult = 1;
result = Prime * result + ((id = =NULL) ? 0:id.hashcode ());
returnResult
}

@Override
PublicBooleanEquals (Object obj) {
if( This= = obj)
returntrue;
if(obj = =NULL)
returnfalse;
if(GetClass ()! = Obj.getclass ())
returnfalse;
User other = (user) obj;
if(id = =NULL) {
if(Other.id! =NULL)
returnfalse;
}Elseif(!id.equals (Other.id))
returnfalse;
returntrue;
}

PublicUser (Integer ID) {
Super();
This. id = ID;
}

} 

The person overrides the Equals and Hashcode methods based on the ID, so that when HashSet adds people, the people object that duplicates the ID is treated as the same people object.

Package Com.ddy;


ImportJava.util.HashSet;
ImportJava.util.Set;

PublicclassTest {
PublicStaticvoidMain (string[] args) {
User user1 =NewUser (1);
User user2 =NewUser (1);
set<user> users =NewHashset<> ();
Users.add (User2);
Users.add (user1);
System.out.println (users);
}
}

Output result:[[email protected]]

Java overrides the Equals method and the Hashcode method

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.