The Equals method in Java programming uses full solution _java

Source: Internet
Author: User

Use the following example to grasp the usage of equals

Package cn.galc.test;

public class Testequals {public
  static void Main (string[] args) {
    /**
     * Here uses the construction method Cat () to new out two cats in heap memory,
     * The color,weight,height of these two cats are the same,
     but C1 and C2 will never be equal, because C1 and C2 are the objects of two cats in the heap memory, which contain the address of the
     two cats. But since two cats are stored in two different spaces in the heap memory,
     * So C1 and C2 each have different addresses, so C1 and C2 will never be equal.
     */
    Cat C1 = new Cat (1, 1, 1);
    Cat C2 = new Cat (1, 1, 1);
    System.out.println ("c1==c2 result is:" + (C1==C2));//false System.out.println ("C1.equals (
    C2) result is:" +c1.equals (C2)) //false
  }
}

class Cat {
  int color, weight, height;

  public Cat (int color, int weight, int height) {
    this.color = color;
    This.weight = weight;
    this.height = height;
  }
}

Draw a memory analysis diagram to analyze the results of C1 and C2 comparisons

Program:

Cat C1 = new Cat (1,1,1);

Cat C2 = new Cat (1,1,1);

After the execution, the layout in memory is shown in the following illustration,

C1 point to an object, C2 also points to an object, C1 and C2 contain the address of the two cat objects stored in the heap memory, because the two cat objects are located in different storage space, so the C1 and C2 the address is not equal to the same, Therefore, C1 and C2 are certainly not equal in reference objects. Therefore carries out: "System.out.println (C1==C2);" The printed result must be false. So you're new out of two objects, you can rest assured that the two objects are always different references, the same words will be covered by one of them, this is not. C1 is not equal to C2 comparison is C1 and C2 the contents of the two references, because the new out of the two objects of their references will never be the same, so C1 and C2 the contents of the two references will never be the same, so C1 can never be equal to C2. So by comparing the references of two objects, you can never make two objects equal, exactly the same.

To determine whether two objects are equal, you can't compare two objects for equality, which is never equal, because the reference to two objects is never equal, so the correct comparison method is to compare the two objects directly, comparing the two objects ' essence is not the same, That is, the contents of the two objects are not the same, and determine whether the two objects are equal by comparing the property values of the two objects.

The object class provides a Equals () method to compare the contents of two objects, so we can use this method to compare whether two objects are logically "equal". For example: C1.equals (C2); This is to invoke the Equals () method inherited from the object class, and to get the definition of the Equals method in the object class by looking up the API documentation is as follows:

public boolean equals (Object obj)

The default implementation of the Equals () method provided in the object class is to compare the current object's reference to the one that you want to compare with the reference they point to is the same object, which is the same as "C1==c2", "C1.equals (C2)" and "C1==C2" is completely equivalent. Therefore, directly using the inherited equals () method can not directly compare the content of two objects is the same, for this reason, we have to rewrite the Equals () method to change the default implementation of this method.

Below, in the Cat class, Rewrite the inherited Equals () method:

Class Cat {
  int color, weight, height;

  public Cat (int color, int weight, int height) {
    this.color = color;
    This.weight = weight;
    this.height = height;
  }
  
  /**
   * Here is an override of the Equals () method inherited from the object class to change the default implementation of this method,
   * To determine whether two objects are logically equal through our own defined implementations.
   * Here we define if two cats have the same color,weight,height,
   * Then we think the two cats are logically identical, that is, the two cats are "equal".
   */Public
  Boolean equals (Object obj) {
    if (obj==null) {return
      false;
    }
    else{
      /**
       * instanceof is an object operator.
       the * object operator is used to determine whether an object belongs to an instance of a specified class or a specified subclass.
       * The object operator is a combination of word instanceof.
       * The operator is a binocular operator, the expression on the left is an object, and the expression on the right is a class, * The result of the
       operation is true if the object on the left is an object created by the right class, or false.
       */
      if (obj instanceof cat) {
        cat c = (cat) obj;
        if (c.color==this.color && c.weight==this.weight && c.height==this.height) {return
          true;
        }
      }
    }
    return false;
  }
}

At this time the Print command is executed in the Main method again:

public static void Main (string[] args) {
    /**
     * Here uses the construction method Cat () to new two cats in the heap memory,
     * The color,weight of these two cats, The height is all the same,
     * but C1 and C2 will never be equal, because C1 and C2 are all references to two cats in the heap memory, which
     contain addresses to find the two cats, but since two cats are stored in two different spaces in the heap memory,
     * So C1 and C2 each have different addresses, so C1 and C2 will never be equal.
     */
    Cat C1 = new Cat (1, 1, 1);
    Cat C2 = new Cat (1, 1, 1);
    System.out.println ("c1==c2 result is:" + (C1==C2));//false System.out.println ("C1.equals (
    C2) result is:" +c1.equals (C2)) ;//true
  }

This time the result is different from the last time you did not rewrite the Equals () method:

"SYSTEM.OUT.PRINTLN (c1 = = C2);" The printed result is still false, because here is the comparison of two objects, the contents of the two references are certainly not equal, and will never be equal, so the printed results must be false.

"System.out.println (c1.equals (C2));" The result printed is true, because we have overridden the Equals () method in the Cat class, changing the default implementation of this method, we change the implementation of the method to the fact that the two objects are real and are all cats, and their color, height and weight ( Weight) are the same, then the two cats are logically identical, the identical two cats, that is, the two cats are "equal". So the results printed here are true.

So how do you compare two string objects for equality?

Look at the following example:

public class Testequals {public
  
  static void main (string args[]) {
    string S1 = new String ("Hello");
    String s2 = new string ("Hello");
    System.out.println ("S1 = = S2 result is:" + (S1 = = s2))//false
    System.out.println ("s1.equals (S2) The result is:" +s1.equals (S2)) ;//true
  }
}

This time is to compare two string objects for equality:

System.out.println (S1 = = s2);

The printed result is still fase, because it compares the references of the S1 and S2 two string objects, and the reference of two objects is never equal, so the result printed is false.

System.out.println (s1.equals (S2));

The printed result is true because the object class is overridden in the String class (all classes inherit from the object class, and the string class is certainly no exception, and inherits from the parent class with all the properties and methods of the parent class). So there is also the Equals () method in the Sting class, and the Equals () method, which is overridden by the inherited Equals () method, changes the default implementation of this method,

In the string class, the implementation of the Equals () method is overridden by comparing the current string object with the specified string object, the specified string object cannot be empty and the character sequence of the object is the same as the string sequence of the current string object, if these conditions are satisfied. Then the two string objects are equal.

So the S2 here has satisfied the condition, so the result of the printout is true.

After comparing two objects in a class to see if they are equal, first go to the API document to find whether the class overrides the Equals () method inherited from the object class. If the Equals () method is overridden, then the equivalent of two objects is invoked when the Equals () method is overridden, and if there is no rewrite, the call is called directly from the inherited Equals () method from the object class, and the Equals () is used. Method The default implementation to compare two objects for equality. Therefore, each class can override the Equals () method inherited from the object class as needed.

For a class in an API document, if a class can be used directly without introducing a package, the class must be in the Java.lang package, such as the String class here, which can be used directly, so the string class must be inside the Java.lang package. Use a class to see which package is introduced in this class, and then go to this package to find this class, do not introduce the package class must be located in the Java.lang inside, directly to the java.lang inside to find it.


Generally, when designing a class, you need to override the Equals method of the parent class, and when overriding this method, you need to design the following rules:
1, Reflexivity: The return value of any reference value X,x.equals (x) 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 does not change, the result of the object comparison should not change any more
5 , Non-null: The return value of any Non-null reference value x,x.equals (NULL) must be false
 
For example:

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 age) {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, name and age are the same. Of course, you can add other attributes, such as the need for the same ID number, to be judged as the same person, you can add to the Equals method of identification number of the judge!

Summary: To compare the equality of two objects, we use the Equals () method to determine if the equality of two objects is defined by the implementation of the Equals () method, which makes it more flexible to use equals () method to compare whether two objects in the same class are equal in different classes.

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.