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