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