Why is the Equals () method rewritten?
Determines whether two objects are logically equal, such as determining whether instances of two classes are equal based on the member variables of the class, whereas inheriting the Equals method in object can only determine whether two reference variables are the same object. This way we often need to rewrite the Equals () method.
When we add elements to a collection that does not have duplicates, the objects are often stored in the collection, and we need to first determine whether there are known objects in the collection, so we must override the Equals method.
How do I rewrite the Equals () method?
Overriding the requirements of the Equals method:
1, Reflexivity: For any non-null reference x,x.equals (x) should return true.
2, symmetry: for any reference to x and Y, if X.equals (y) returns True, then Y.equals (x) should also return true.
3, transitivity: For any reference x, Y, and Z, if X.equals (y) returns True,y.equals (Z) returns True, then X.equals (z) should also return true.
4. Consistency: If the objects referenced by x and y do not change, then repeated calls to X.equals (Y) should return the same result.
5, non-nullability: for any non-null reference x,x.equals (NULL) should return FALSE.
1. The principle of reflexivity
public Class Person {private String name; Public person (String name) {this.name = name; } public String GetName () {return name; } public void SetName (String name) {this.name = name; } @Override public boolean equals (Object obj) {if (obj instanceof person) {person person= (Pers ON) obj; Return Name.equalsignorecase (Person.getname (). Trim ()); } return false; } public static void Main (string[] args) {person p1=new person ("Zhang San"); Person P2=new person ("Zhang San"); list<person> list = new arraylist<person> (); List.add (p1); List.add (p2); SYSTEM.OUT.PRINTLN ("Whether contains Zhang San:" +list.contains (p1)); SYSTEM.OUT.PRINTLN ("Whether contains Zhang San:" +list.contains (p2)); }}
The list contains this generated person object, and the result should be true, but the actual result: this takes into account the problem of string spaces, and the space before and after the removal.
Contains Zhang San: true
Contains Zhang San: false
Why is the second one false? The reason is that the list checks whether the element is contained by invoking the Equals method of the object, that is, contains (P2) is passed in order to execute P2.equals (p1), P2.equals (P2), as long as a return true, The result is true. But here P2.equals (p2) returns false? Since we cut the space before and after the character, the comparison of P2.equals (P2) is actually: "Zhang San". Equals ("Zhang San"), one with a space, and one without a space.
This violates the principle of the reflexive nature of equals: X,x.equals (x) should return true for any non-null reference.
This can be solved just by removing the trim method.
2. The principle of symmetry
The above example is not very good, what happens if we pass in a null value? Add a statement: person p2=new person (null);
Results:
| 1 2 |
是否包含张三:trueException in thread "main"java.lang.NullPointerException |
Because the name of P2 is a null value when executing p2.equals (p1), a null pointer exception is reported when the Name.equalsignorecase () method is called.
This is not followed by the principle of symmetry when you overwrite the Equals method: for any case where x, Y is applied, if you want X.equals (Y) to return True, then y.equals (x) should also return true.
The Equals method should be used to determine whether a null value should be added:
@Override public boolean equals (Object obj) { if (obj instanceof person) {person person= (person) obj; if (person.getname () = = NULL | | name = NULL) { return false; } else{ return Name.equalsignorecase (Person.getname ()); } } return false; }
3. The principle of transitivity
Now we have an employee class that inherits from the person class:
public Class Employee extends person{private int id; public int getId () {return id; } public void setId (int id) {this.id = ID; Public Employee (String name,int ID) {super (name); This.id = ID; TODO auto-generated Constructor stub} @Override public Boolean equals (Object obj) {if (obj instanceof Employee) {Employee E = (employee) obj; return super.equals (obj) && e.getid () = = ID; } return Super.equals (obj); } public static void Main (string[] args) {Employee E1=new employee ("Zhang San", 12); Employee E2=new employee ("Zhang San", 123); person P1 = new Person ("Zhang San"); System.out.println (P1.equals (E1)); System.out.println (P1.equals (E2)); System.out.println (E1.equals (E2)); }}
Only if the name and ID are the same employee, avoid the same name. Defined in main, two employees and a social homeless, although the same name but certainly not the same person. The result of the operation should be three false. But:
True
True
False
P1 altogether equals E1, also equals E2, is not an instance of the same class equal? Because P1.equals (E1) is determined by calling the Equals method of the parent class, it uses the instanceof keyword to check whether E1 is an instance of person, and because the employee and person are inheritance, the result is true. But let go is not established, e1,e2 is not equal to P1, this is also a violation of the principle of symmetry of a typical case.
E1 actually not equal to E2? E1.equals (E2) calls the employee's Equals method, not only to determine the same name and judge work number is the same, the work number of the two are different, not equal when the pair. But P1 equals E1, also equals e2,e1 but not equal to E2, there is a contradiction, the equation is not passed because it violates the transitive principle of equals: For instance object x, Y, z; if X.equals (y) returns True,y.equals (Z) returns True, Then X.equals (z) should also return true.
This occurs because the parent class uses the INSTANCEOF keyword (whether it is a particular class or an instance of its subclass) to determine if it is an instance object of a class, which can easily "exploit" the subclass. To solve it is also very simple, using getclass for type judgment, the Equals method of the person class is modified as follows:
@Override public boolean equals (Object obj) { if (obj! = null && obj.getclass () = = This.getclass ()) { Person person= (person) obj; if (person.getname () = = NULL | | name = NULL) { return false; } else{ return Name.equalsignorecase (Person.getname ()); } } return false; }
4, must overwrite Hashcode method So the result is three false.
Overwrite the Equals method must overwrite the Hashcode method, which is known to Javaer. The reason is that the underlying processing mechanism of HASHMAP is to save the map bar as an array, the key of which is the processing mechanism of the array subscript: the subscript of the array is determined by the return value of the Hashcode method passed in to the element, if the array location already has a map entry, and equal to the incoming key value is not processed, if not equal is overwritten; if there is no entry for the array position, it is inserted and added to the list of map entries. Similarly check if the key exists and is based on the hash to determine the civilian, and then traverse the lookup key value.
So what does the Hashcode method of the object return? He is the hash code for an object that is generated by a local method with the object class, ensuring that each object has a hash code.
Specific can be seen in another blog post: http://www.cnblogs.com/silence-hust/p/4510574.html
?
Some points to note in Java overriding the Equals method