Java equals = =

Source: Internet
Author: User

 Packagecom.cwcec.test;classdemo{}classMydemoextendsdemo{} Public classFielddemo { Public Static voidMain (string[] args) {Mydemo Mydemo=NewMydemo (); Object Object=Mydemo; Demo Demo=Mydemo; System.out.println (ObjectinstanceofMydemo); System.out.println (MydemoinstanceofDemo); System.out.println (DemoinstanceofMydemo);        System.out.println (Demo.equals (Mydemo));                System.out.println (Mydemo.equals (demo)); String s= "123"; String S1=NewString ("123"); System.out.println (S= = "123"); System.out.println (S1= = "123"); System.out.println (S==S1);            System.out.println (S.equals (S1)); }  } 
Output:truetruetruetruetruetruefalsefalsetrue
Equals ()

There is this equals () method in the Superclass object, which is used primarily to compare the equality of two objects. The source code of the method is as follows:

public boolean equals (Object obj) {    return (this = = obj);    }

We know that all objects have identities (memory addresses) and states (data), while "= =" compares the memory addresses of two objects, so the Equals () method using object is to compare the memory addresses of two objects for equality, even if Object1.equals (object2 True indicates that EQUALS1 and EQUALS2 actually refer to the same object. Although sometimes the Equals () method of object satisfies some of our basic requirements, we have to be clear that most of the time we are comparing two objects, this time the Equals () method of object is not allowed, in fact the JDK, String, Package classes such as Math override the Equals () method. The following is the Equals () method of string:

 Public Booleanequals (Object anobject) {if( This==anobject) {        return true; }    if(AnObjectinstanceofString) {String anotherstring=(String) AnObject; intn =count; if(n = =anotherstring.count) {CharV1[] =value; CharV2[] =Anotherstring.value; inti =offset; intj =Anotherstring.offset;  while(n--! = 0) {            if(v1[i++]! = v2[j++])            return false; }        return true; }    }    return false; }

For this snippet: if (v1[i++]! = v2[j++]) return false; we can see very clearly that the Equals () method of the string is a content comparison, not a reference comparison. As for the other packaging classes are similar.

In the Java specification, its use of the Equals () method must follow several rules:

The Equals method implements an equality relationship on a non-null object reference:

1, reflexivity: for any non-null reference value X,x.equals (x) should return true.

2. Symmetry: for any non-null reference value x and Y, x.equals (y) should return true if and only if Y.equals (x) returns True.

3, transitivity: for any non-null reference value x, Y, and Z, if X.equals (y) returns True, and Y.equals (z) returns True, then X.equals (z) should return true.

4. Consistency: for any non-null reference value x and Y, multiple calls to X.equals (Y) always return TRUE or always return false, provided that the information used in the Equals comparison on the object has not been modified.

5 . x,x.equals (null) should return FALSE for any non-null reference value.

For the above rules, we are best to follow in the process of use, otherwise there will be unexpected errors.

To compare in Java, we need to choose the appropriate comparison method based on the type of comparison:

1) object domain, using the Equals method.
2) Type-safe enumeration, using equals or = =.
3) possible null object domain: Use = = and equals.
4) array field: Use Arrays.equals.
5) raw data types except float and double: use = =.
6) float type: Use float.foattointbits to convert to int type, then use = =.
7) double type: Use Double.doubletolongbit to convert to a long type, and then use = =.

As for 6), 7) Why conversion is required, we can refer to the Equals () method of their corresponding encapsulated class, the following is the float class:

 Public Boolean equals (Object obj) {    returninstanceof  Float)           && ( Floattointbits (((Float) obj). value) = = Floattointbits (value))    ;

Why, there are two points mentioned:

However, there is, Exceptions:if F1 and F2 both Representfloat.nan, then the Equals method returns true, even though float.nan==falsewhile -0.0f, or Viceversa, the equal test has the valuefalse, even though 0.0f==-0.0ftrue.
Use GetClass for type determination in equals ()

When we overwrite the Equals () method, it is generally recommended to use GetClass for type judgments, not instanceof. We all know that the function of instanceof is to determine whether its left object is an instance of its right class and returns a Boolean type of data. Can be used to determine whether an instance of a subclass in an inheritance is an implementation of a parent class. Note the following sentence: can be used to determine whether the instance of the subclass in the inheritance is the implementation of the parent class, it is this sentence in mischief. Let's take a look at the following example (151 recommendations from the high-quality code to improve Java programs).

Parent class: Person

 Public classPerson {protectedString name;  PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }         PublicPerson (String name) { This. Name =name; }         Public Booleanequals (Object object) {if(ObjectinstanceofPerson ) {Person P=(person) object; if(P.getname () = =NULL|| Name = =NULL){                return false; }            Else{                returnname.equalsignorecase (P.getname ()); }        }        return false; }}

Sub-Category: Employee

 Public classEmployeeextendsperson{Private intID;  Public intgetId () {returnID; }     Public voidSetId (intID) { This. ID =ID; }     PublicEmployee (String name,intID) {        Super(name);  This. ID =ID; }        /*** override Equals () method*/     Public Booleanequals (Object object) {if(ObjectinstanceofEmployee) {Employee e=(Employee) object; return Super. Equals (object) && e.getid () = =ID; }        return false; }}

The above parent class person and subclass employee both override Equals (), but the employee has an id attribute that is more than the parent class. The test procedure is as follows:

 Public class Test {    publicstaticvoid  main (string[] args) {        new Employee ("Chenssy");         New Employee ("Chenssy");         New Person ("Chenssy");                System.out.println (P1.equals (E1));        System.out.println (P1.equals (E2));        System.out.println (E1.equals (E2));}    }

The above defines two employees and an ordinary person, although they have the same name, but they certainly are not the same person, so it is supposed that the output should all be false, but backfired, the result is: true, true, false.

For that e1!=e2 we are very easy to understand because they need not only to compare name, but also to compare IDs. But P1 is equal to E1 is also equal to E2, which is very strange, because E1, E2 is clearly two different classes, but why this situation? First P1.equals (E1) is the Equals method that calls P1, which uses the instanceof keyword to check if E1 is a person class, and here we look at instanceof: Determine if its left object is an instance of its right class. It can also be used to determine whether an instance of a subclass in an inheritance is an implementation of a parent class. They have an inheritance relationship and will certainly return true, and the two name is the same, so the result must be true.

So the situation above is the use of the keyword instanceof, which is very easy to "special loophole." Therefore , it is recommended to use GetClass for type judgment when you overwrite equals. Instead of using instanceof.

Java 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.