Download Java interview book:Http://download.csdn.net/source/3563084
Set and list are two sub-interfaces of collection. The elements in set must be unique. Therefore, the equals method must be rewritten. For the hashset method, the hashcode method must be rewritten.
When an element is added to a hahset, It is not added to determine whether the element already exists. Therefore, the comparison between the two instance objects is involved.
To compare two instance objects:
(1) Determine whether the return values of hashcode are the same. If they are different, they are not the same instance object and can be added; otherwise, they are included in step (2;
(2) Determine whether the return value of the equals method is true. If it is true, it is the same; otherwise, it is different.
The following two methods are implemented:
Public class userinfo {private string username; private string password; Public userinfo () {} public userinfo (string _ username, string _ password) {This. username = _ username; this. password = _ password ;}@ overridepublic int hashcode () {final int prime = 31; int result = 1; Result = prime * result + (username = NULL? 0: username. hashcode (); Result = prime * result + (Password = NULL? 0: password. hashcode (); return result;} @ overridepublic int equals (Object OBJ) {If (this = OBJ) {return true;} If (OBJ = NULL) {return false;} If (! (OBJ instanceof userinfo) {return false;} final userinfo Other = (userinfo) OBJ; If (this. Username = NULL) {If (other. GetUserName ()! = NULL) {return false ;}} else if (! This. username. Equals (other. GetUserName () {return false;} If (this. Password = NULL) {If (other. GetPassword ()! = NULL) {return false ;}} else if (! This. Password. Equals (other. GetPassword () {} return true;} // saves the get and set methods for attributes}