The following is a java4android video tutorial from marschen.
Main content of this set.
1. Where is the equals function.
2. Functions of the equals function.
3. Method for rewriting the equals function.
A. Equals is included in the object. The object is the parent class of all classes.
Therefore, all classes inherit the equals method.
B. Check whether the two references point to the same address in the heap memory. or
Is the same object.
Code on
The equals function is used to compare whether the content of two objects is equal.
Normally, whether the content of two objects is equal. The two conditions must be met.
A. The object type is the same (you can use the instanceof operator for comparison ).
B. The values of the member variables of the two objects are identical.
class User{ String name; int age; public boolean equals(Object obj){ if(this == obj){ return true; } boolean b = obj instanceof User; if(b){ User u = (User)obj; if(this.age == u.age && this.name.equals(u.name)){ return true; } else{ return false; } } else{ return false; } }}
class Test{public static void main(String args[]){User u1 = new User();User u2 = new User();User u3 = new User();u1.name = "zhangsan";u1.age = 12;u2.name = "lisi";u2.age = 12;u3.name = "zhangsan";u3.age = 12;System.out.println(u1.equals(u2));System.out.println(u1.equals(u3));//User u3 = u1;//boolean b1 = u1 == u2;//boolean b2 = u1 == u3;//System.out.println(b1);//System.out.println(b2);//boolean b1 = u1.equals(u2);//System.out.println(b1);}}