Equals method of Object Class

Source: Internet
Author: User

The equals method only determines whether two variables point to the same memory area to determine whether they are equal,

 
Students [0] = new student ("Huaihua College", "Small Group", 22); students [1] = new student ("Huaihua College", "Small Group", 22 ); system. out. println (students [0]. equals (students [1]);

The attributes of these two student objects are the same, but equals is different. To compare attributes, you must implement the equals method.
Override the equals method in student

 
@ Override public Boolean equals (Object otherobject) {If (this = otherobject) // The two objects are the same, obviously equal return true; If (otherobject = NULL) // If otherobject is null, return false; If (getclass ()! = Otherobject. getclass () // if the two classes are different, false return false is returned; // ensure that the otherobject is a student class, and then determine whether the attribute value is equal to student Other = (student) otherobject; return this. getage () = Other. getage () & this. getname () = Other. getname () & this. school = Other. school ;}

some people prefer to use (! (Otherobject instanceof student) instead of (getclass ()! = Otherobject. getclass () to determine whether the
otherobject is a student class, but there is a problem: the subclass can also be an instance of the parent class.
equals must meet the following five features:
(1) Self-inverse, for any non-empty variables X, X. equals (x) must return true;
(2) symmetry, X. equals (Y) and Y. equals (x) returns the same value.
(3) transmission, if X. equals (y) returns true, Y. if equals (z) returns true, X. equals (z) should also return true;
(4) Consistency. If the object pointed to by the variable X and Y does not change, call X again. the return values of equals (y) are the same.
(5) for any non-null variables X, X. equals (null) must return false

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.