As we all know, in Java, for the comparison of objects, if "= =" is compared with the object reference, and equals is the content of the object to compare.
In general, when designing a class, we need to override the Equals method of the parent class, and when overriding this method, we need to design the following rules:
1. Reflexivity: The return value of X,x.equals (x) for any reference value must be true.
2. Symmetry: For any reference value x, Y, the return value of X.equals (Y) must be true if and only if the return value of Y.equals (x) is true;
3, transitivity: if X.equals (y) =true, y.equals (z) =true, then X.equals (z) =true
4, Consistency: If the object participating in the comparison has not changed, then the results of the object comparison should not have any change
5, non-nullability: any non-null reference value x,x.equals (NULL) The return value must be false
For example:
Java code
- Public class People {
- private String FirstName;
- private String LastName;
- private int age;
- Public String Getfirstname () {
- return firstName;
- }
- public void Setfirstname (String firstName) {
- this.firstname = firstName;
- }
- Public String Getlastname () {
- return lastName;
- }
- public void Setlastname (String lastName) {
- this.lastname = lastName;
- }
- public int getage () {
- return age;
- }
- public void Setage (int.) {
- this.age = age;
- }
- @Override
- public boolean equals (Object obj) {
- if (this= = obj) return true;
- if (obj = = null) return false;
- if (getclass () = Obj.getclass ()) return false;
- People other = (people) obj;
- if (age! = other.age) return false;
- if (firstName = = null) {
- if (other.firstname! = null) return false;
- } Else if (!firstname.equals (other.firstname)) return false;
- if (lastName = = null) {
- if (other.lastname! = null) return false;
- } Else if (!lastname.equals (other.lastname)) return false;
- return true;
- }
- }
In this example, we stipulate that a person is the same person if the surname, first name, and age are the same. Of course you can also add other properties, such as the need to have the same ID number, in order to determine the same person, you can add to the Equals method to determine the ID number!
The Equals () method in Java