= = in Java and equals ()

Source: Internet
Author: User

= = Usage

1. Compare basic data types, if two values are the same, the result is true

2. When comparing references, if the reference points to the same object in memory, the result is true

Equals () Usage

Function prototype: public boolean equals (Object obj)

1. Returns True when the object referenced by the parameter obj is the same object as the current object, otherwise false

Since the two have the same effect, why do we have to make a equals () method? Because the = = operator does not allow us to overwrite, that is, it restricts our expression.

Example:

1 /**2  * @authorXiaoyuer3  *4  */5  Public classStudents6 {7     Private intAge ;8     PrivateString name;9     Ten      PublicStudents (intage,string name) One     { A          This. Age =Age ; -          This. Name =name; -     } the  -      Public intGetage () { -         returnAge ; -     } +  -      Public voidSetage (intAge ) { +          This. Age =Age ; A     } at  -      PublicString GetName () { -         returnname; -     } -  -      Public voidsetName (String name) { in          This. Name =name; -     }     to } +  -  classequaltest the { *      Public Static voidMain (String args[]) $     {Panax NotoginsengStudents e1 =NewStudents (18, "Zhang San"); -Students e2 =NewStudents (18, "Zhang San"); the          +SYSTEM.OUT.PRINTLN (e1 = =E2); A System.out.println (E1.equals (E2)); the     } + } -equals uses
equals uses

Operation result :

False

False

results : using the "= =" and using the Equals () method result is false, stating that the Equals () function is intended to determine whether the reference of two objects is the same

The JDK provides an overlay mechanism:

There are classes in the JDK class that cover the Equals () method of the Oject class, and the rule is: if two objects are of the same type, and the content is consistent, return True, these classes are:
Java.io.file,java.util.date,java.lang.string, packing class (integer,double, etc.)

Example:

1  classequaltest2 {3      Public Static voidMain (String args[])4     {        5String e1=NewString ("AAA");6String e2=NewString ("AAA");7 8SYSTEM.OUT.PRINTLN (e1 = =E2);9 System.out.println (E1.equals (E2));Ten     } One}
JDK Overlay mechanism

Operation result :

False

True

The result is that the Equals () method is overridden in string to make its meaning compare to the consistency of the contents of the two objects

Expand promotion : Copy Equals () method, achieve compare other content

We should also note that the Java language requirements for Equals () are as follows, and these requirements must be followed:
• Symmetry: If X.equals (y) returns "true", then Y.equals (x) should also return "true".
• Reflectivity: X.equals (x) must return "true".
• Analogies: 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", as long as the X and Y contents remain constant, the return is "true" no matter how many times you repeat X.equals (y).
• In any case, x.equals (NULL) will always return "false", and X.equals (and X objects of different types) will always return "false".
These five points are the criteria that must be adhered to when overriding the Equals () method, and if the violation will result in unexpected results, please be sure to follow.

Equals () equal to two objects, hashcode () must be equal;
The Equals () method is not equal to two objects, and hashcode () may be equal. (There may be a hash conflict).

1 /**2  * @authorXiaoyuer3  *4  */5  Public classStudents6 {7     Private intAge ;8     PrivateString name;9     Ten      PublicStudents (intage,string name) One     { A          This. Age =Age ; -          This. Name =name; -     } the      - @Override -      Public Booleanequals (Object obj) -     { +         //1. Determine if the incoming object is the same as the object obj address -         if( This==obj) +            return true; A          at         //2.x.equals (NULL), Return forever is "false"; -         if(obj = =NULL) -            return false; -          -         //1. Reflective -         if(GetClass ()! =Obj.getclass ()) in            return false; -          toStudents other =(Students) obj; +          -         if(Name = =NULL)  the         { *            if(Other.name! =NULL) $                //name is not empty, and is not equal, returns falsePanax Notoginseng                return false; -         } the         Else if(!name.equals (other.name)) +             return false; A          the         //Age does not want to wait, return false +         if(age!=other.age) -             return false; $          $         return true; -  -     } the  -     //The hashcode () method is also replicated after the Equals () method is replicated to ensure that the same object returns the same HashcodeWuyi @Override the      Public inthashcode () -     { Wu         intresult = 1; -         Final intPrime = 31; Aboutresult = Prime * result + ((name = =NULL)? 0: Name.hashcode ()); $result = Prime * result +Age ; -         returnresult; -     } -      A      Public intGetage () { +         returnAge ; the     } -  $      Public voidSetage (intAge ) { the          This. Age =Age ; the     } the  the      PublicString GetName () { -         returnname; in     } the  the      Public voidsetName (String name) { About          This. Name =name; the     }     the } the  +  classequaltest - { the      Public Static voidMain (String args[])Bayi     {         theStudents e1=NewStudents (18, "Zhang San"); theStudents e2=NewStudents (18, "Zhang San"); -  -SYSTEM.OUT.PRINTLN (e1 = =E2); the System.out.println (E1.equals (E2)); the     } the}
replication equals

Results:

False

True

= = in Java and equals ()

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.