Hashcode () and equals methods in Java class

Source: Internet
Author: User

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}
 
Related Article

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.