The Equals () method that determines whether objects are equal in Java uses the tutorial _java

Source: Internet
Author: User
Tags class manager comparable

The Equals method in the object class is used to detect whether an object is equal to another object. In the object class, this method determines whether two objects have the same reference, and if two objects have the same reference, they must be equal. From this point of view, it is reasonable to use it as the default operation. For most class classes, however, this kind of judgment doesn't make sense, for example, it doesn't make sense to compare two printstream equality in this way. However, it is often necessary to detect the equality of two object states, and if the states of two objects are equal, the two objects are considered equal. Therefore, it is common to override the equals comparison in a custom class.

Here is a suggestion to write a perfect Equals () method:

(1) The explicit parameter is named Otherobject and later needs to be converted into a variable called other

(2) Detect whether this and Otherobject refer to the same object:

if (This==otherobject) return true;

This statement is just an optimization. In fact, this is a frequently used form. Because computing this equation is much less costly than comparing fields in a class one by one.

(3) detects whether the otherobject is null, and returns FALSE if null. This test is very necessary.

if (otherobject==null) return false;

(4) Compare whether this and otherobject belong to the same class, and if the semantics of equals change in each subclass, use GetClass () instrumentation, which takes itself as the target class

if (GetClass ()!=otherobject.getclass ()) return false;

If all subclasses have the same semantics, the instanceof detection is used

if (!) ( Otherobject instanceof ClassName)) return false;

(5) Convert Otherobject to a variable of the appropriate type:

ClassName other= (ClassName) otherobject;

(6) Now start comparing all the fields that need to be compared. Use = = to compare the base Type field, and use equals to compare the Object field. Returns True if all fields match, otherwise returns false;

Return Field1==other.field1&&field2.equals (OTHER.FIELD2)

If you redefine equals in a subclass, you must include call Super.equals (other) in it. If the test fails, it cannot be equal. If the fields in the superclass are equal, the instance fields in the subclass are compared.

For fields of an array type, you can use the static Arrays.equals method to detect whether the corresponding elements are equal.

Take a look at a few string comparison examples:

String a = "abc"; 
String B = "abc"; 
String c = new String ("abc"); 
String d = new String ("abc"); 
System.out.println (A = = B); True because the string constants in Java are shared, only one copy 
System.out.println (a = = c);//False A and C belong to 2 different objects 
System.out.println (a.equals (c)); True because the Equals method of a String object compares values in an object, returns True. (different than the Equals method of object) 
System.out.println (C==d); False C and D are unequal System.out.println (C.equals (d)), although the values within the object are the same, but belong to 2 different objects 
;//True 

In short, when you compare string constants, you are equal to the result returned by equals, and you use equals when you want to compare the value of a string object.

See the example of a equals usage:

Package chapter05. 
 
Equalstest; 
 
Import java.util.*; public class Equalstest {public static void main (string[] args) {Employee Alice1 = new Employee ("Alice Adams", 7500 
  0, 1987, 12, 15); Employee alice2 = Alice1; 
  Reference the same object employee Alice3 = new Employee ("Alice Adams", 75000, 1987, 12, 15); 
 
  Employee Bob = new Employee ("Bob Brandson", 50000, 1989, 10, 1); 
 
  System.out.println ("Alice1 = = Alice2:" + (Alice1 = = Alice2)); 
 
  System.out.println ("Alice1 = = Alice3:" + (Alice1 = = Alice3)); 
 
  System.out.println ("Alice1.equals (ALICE3):" + (Alice1.equals (alice3))); 
 
  System.out.println ("Alice1.equals (Bob):" + (Alice1.equals (Bob))); 
 System.out.println (Bob.tostring ()); 
  Class Employee {public employee (String N, double S, int year, int month, int day) {name = N; 
  Salary = s; 
  GregorianCalendar calendar = new GregorianCalendar (year, month, day); 
 Hireday = Calendar.gettime (); Public String GetName () {return name; 
 Public double getsalary () {return salary; 
 Public Date Gethireday () {return hireday; 
  The public void Raisesalary (double bypercent) {Double raise = salary * BYPERCENT/100; 
 Salary + = raise;  @Override public boolean equals (Object otherobject) {//A quick test to objects are identical if 
 
  (This = = Otherobject) return true; 
 
  Must return FALSE if the explicit parameter is null if (Otherobject = = null) return false; 
 
  If the classed don ' t Match,they can ' t be equal if (GetClass ()!= Otherobject.getclass ()) return false; 
 
  Now we know Otherobject are a Non-null employee employee other = (Employee) otherobject; 
    Test whether the fields Hava identical values return name.equals (other.name) && salary = = Other.salary 
 
 && hireday.equals (Other.hireday); @Override public int hashcode () {return 7 * Name.hashcode () + one * new Double (Salary). Hashcode () + 13
    * Hireday.hashcode ();  @Override public String toString () {return getclass (). GetName () + "[name=" + name + ", salary=" + salary + 
 ", hireday=" + Hireday + "]"; 
 private String name; 
 private double salary; 
Private Date Hireday; Class Manager extends Employee {public Manager (String N, double S, int year, int month, int day) {super (n, S, 
  Year, month, day); 
 bouns = 0; 
  @Override public Double getsalary () {Double basesalary = super.getsalary (); 
 return basesalary + bouns; 
 public void Setbouns (double b) {bouns = b; 
  @Override public boolean equals (Object otherobject) {if (!super.equals (Otherobject)) return false; 
  Manager other = (manager) Otherobject; 
 Super equals checked that this and other belong to the same class return bouns = = Other.bouns; 
 @Override public int hashcode () {return Super.hashcode () + * New Double (bouns). Hashcode (); @Override Public String Tostring () {return super.tostring () + "[bouns=" + Bouns + "]"; 
Private double bouns; 

 }

Depth
The following is divided into 2 classes, based on whether the class overrides Equals () method.
(1) If a class does not overwrite the Equals () method, when it compares two objects by equals (), it actually compares two objects to be the same object. This is equivalent to comparing the two objects by "= =".
(2) We can override the Equals () method of the class to let equals () compare the equality of two objects in other ways. The common practice is that the Equals () method returns True if the contents of two objects are equal, otherwise, returns FASLE.
Below, for example, the above 2 kinds of cases are described.
1. "No coverage of the Equals () method"
the code is as follows (Equalstest1.java):

Import java.util.*;
Import java.lang.Comparable;

/**
 * @desc the test procedure for Equals ().

 */Public
class equalstest1{public

 static void Main (string[] args) {
  //New Person object with 2 identical content
  // Then use equals to compare whether they are equal
  to person p1 = new person ("Eee");
  person P2 = new Person ("Eee");
  System.out.printf ("%s\n", P1.equals (p2));
 }

 /**
  * @desc Person class.
  * *
 private static class person {
  int age;
  String name;

  Public person (String name, int age) {
   this.name = name;
   This.age = age;
  }

  Public String toString () {return
   name + '-' +age}}}


Run Result:

Copy Code code as follows:
False

Result analysis
We use P1.equals (p2) to "compare P1 and P2 equality". In effect, the Object.java equals () method of the call (P1==P2) is invoked. It is the comparison between "P1 and P2 is the same object".
The definitions of P1 and P2 know that they are the same, but they are two different objects! Therefore, the return result is false.

2. "Coverage of Equals () method"
We modify the above Equalstest1.java: Overwrite Equals () method.
The code is as follows (Equalstest2.java):

 import java.util.*; import java.lang.Comparable;
 /** * @desc the test procedure for Equals (). /public class equalstest2{public static void Main (string[] args) {//New Person object with 2 identical content,//To compare them to equals Pe
  Rson P1 = new Person ("Eee", 100);
  person P2 = new Person ("Eee", 100);
 System.out.printf ("%s\n", P1.equals (p2));
  /** * @desc the person class.
  * * private static class Person {int age;

  String name;
   Public person (String name, int age) {this.name = name;
  This.age = age;
  Public String toString () {return name + '-' +age; /** * @desc Overwrite equals method */@Override public boolean equals (Object obj) {if (obj = null) {return 
   False 
   //If the same object returns True, Vice returns False if (this = = obj) {return true; 
   }//Judge whether the type is the same if (This.getclass ()!= Obj.getclass ()) {return false; 
   person who = (person) obj; 
  Return Name.equals (person.name) && age==person.age; } 
 }
}

Run Result:

Copy Code code as follows:
True

Results Analysis:
We have overridden the Equals () function of person in Equalstest2.java: Returns True if the name and age of the two man objects are equal.
Therefore, the run result returns TRUE.
By the way, Java's requirements for Equals () are mentioned here. Have the following points:
Symmetry: If X.equals (y) returns "true", then Y.equals (x) should also return "true".
Reflectivity: X.equals (x) must return is "true".
Analogy: If X.equals (y) returns "true" and Y.equals (z) returns "true", then Z.equals (x) should also return "true".
Consistency: if X.equals (y) returns "true", the return is "true" whenever the X and Y contents remain unchanged, no matter how many times you repeat X.equals (y).
Non-null, x.equals (NULL), always returns "false", X.equals (and X objects of different types) return forever "false".
Now, review the role of Equals (): Determine whether two objects are equal. When we rewrite equals (), we must not be able to change the role of it!

What is the difference between


equals () and = =?
= =: Its role is to determine whether the address of two objects is equal. That is, to judge that two objects are not the same object.
Equals (): Its role is to determine whether two objects are equal. However, it typically has two uses (described in detail in part 1th above):
     1, the class does not overwrite the Equals () method. Comparing the two objects of the class by Equals () is equivalent to comparing the two objects by "= =".
     2, the class overrides the Equals () method. In general, we all override the Equals () method to have the contents of two objects equal, and if their contents are equal, return True (that is, consider the two objects equal).
below, compare the differences between them by example. The
code is as follows:

Import java.util.*;

Import java.lang.Comparable;
 /** * @desc the test procedure for Equals (). /public class equalstest3{public static void Main (string[] args) {//New Person object with 2 identical content,//To compare them to equals Pe
  Rson P1 = new Person ("Eee", 100);
  person P2 = new Person ("Eee", 100);
  System.out.printf ("P1.equals (p2):%s\n", P1.equals (p2));
 System.out.printf ("P1==P2:%s\n", P1==P2);
  /** * @desc the person class.
  * * private static class Person {int age;

  String name;
   Public person (String name, int age) {this.name = name;
  This.age = age;
  Public String toString () {return name + '-' +age; /** * @desc Overwrite equals method */@Override public boolean equals (Object obj) {if (obj = null) {return 
   False 
   //If the same object returns True, Vice returns False if (this = = obj) {return true; 
   }//Judge whether the type is the same if (This.getclass ()!= Obj.getclass ()) {return false; 
   person who = (person) obj; Return Name.equals (person.name) && Age==peRson.age;

 } 
 }
}

Run Result:

P1.equals (p2): True
p1==p2:false

Results Analysis:
In the Equalstest3.java:
(1) p1.equals (p2)
This is to determine whether the contents of P1 and P2 are equal. Because the person overrides the Equals () method, the Equals () is used to determine whether the contents of the P1 and P2 are equal, precisely P1 and P2, and therefore returns true.
(2) P1==P2
This is to determine whether P1 and P2 are the same object. Returns false because they are newly created two person objects.

Related Article

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.