The difference between equals () and = = and its practical application __java

Source: Internet
Author: User

Equals () and = = are used in Java programming or in the actual availability of the system, but there is a real difference between them. Do not take for granted that equals () and = = function is the same, the following step-by-step to explain the difference between the two.

Phone.java
New phone class, with two private member variables, price and memory, initialized in the constructor.

Package testpackage;

public class Phone {

    private float price;//price
    private int memory;//memory public

    phone (float price, int memory) { C5/>super ();
        This.price = Price;
        this.memory = memory;
    }

Testphone.java
New two mobile phone objects, two private member variables are assigned the same value, using equals () to compare

Package testpackage;

public class Testphone {public

    static void Main (string[] args) {

        phone p1 = new phone (4000f,16);//4000 yuan, 16G memory hand Machine P1 phone
        p2 = new phone (4000f,16);//4000, 16G memory mobile P2 if

        (p1.equals (p2)) {//if P1 equals P2
            System.out.println ("P1 is the same as P2");
        }
        ELSE{//P1 is not equal to P2
            System.out.println ("P1 is not the same as P2");}

Run Result:
P1 and P2 are not the same

Results Analysis:
Although the private member variables of the two mobile objects are all the same, the Equals () run results show that the two objects are different. This is why.
Also, the phone class does not define the Equals () method, where the Equals () method comes in.
I'm sure you all know that all classes in Java inherit Object.class, so all classes inherit the Equals () method in the object class, and to know the nature of the results of the operation, you must look at the Object.class source.
Open the Object.class source to find the location that defines the Equals () method:

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

Found that Object.class gives the definition of the Equals () method, but simply through = = to achieve judgment. and = = is used in Java to determine whether the values stored on the stack are equal. Our basic data types, like int, are used = =, because the basic data types are stored on the stack, also on the stack, and references to reference data types, and the real objects themselves are stored in the heap. Therefore, the Equals () method given here is just a comparison of two objects in memory (that is, addresses) are equal. In this example, two new objects are created in memory, the newly opened up two memory space, the reference address is certainly not the same, the results of the program run is certainly not the same.
But we want to use two mobile phone prices and memory the same to judge the phone is the same, indeed the actual development of our thinking, that should do. Override the Equals () method.

the Equals () method is overridden in Phone.java:

Package testpackage;

public class Phone {

    private float price;//price
    private int memory;//memory public

    phone (float price, int memory) { C4/>super ();
        This.price = Price;
        this.memory = memory;
    }

    @Override public
    Boolean equals (Object obj) {
        if (this = = obj) {//If the reference address is the same, proving to be the same object, of course, same return
            true;
        }
        if (obj ==null) {//If the object is empty, no comparison is necessary, return false directly to False
            ;
        }
        if (!) ( obj instanceof Phone) {//If obj is not an object instance of phone, returns false return False
            ;
        }
        Phone p = (phone) obj;//compilation required, coercion type conversion
        if (This.price==p.price && this.memory==p.memory) {return
            true;< c22/>}
        else{return
            false;   
    }
}

Rerun Testphone.java to view run results:

Run Result:
P1 is the same as P2

Results Analysis:
by overriding Equals (), you can determine whether two mobile objects are equal through private member variables, and if prize and memory are equal, then two mobile objects are equal.

See here, I believe that the Equals () and = = The difference has a certain understanding, but obviously not enough, about the difference between the two, there is a place worth understanding.

new Teststring.java for string testing

Package testpackage;

public class TestString {public

    static void Main (string[] args) {

        String S1 = "I am mobile 1";
        String s2 = new String ("I am mobile 1");

        System.out.println (S1==S2);
        System.out.println (s1.equals (S2));
    }

Run Result:
False
True

Results Analysis:
In Java, a string is a reference data type that exists as an instance object. Therefore, although S1 and S2 seem to be defined differently, they are all new objects, essentially the same.
As mentioned above, = = Compare the reference data type in the stack address is the same, S1 and S2 are new two string objects, of course, opened up two different memory space, the result returned false of course is expected.
But why s1.equals (S2) returns true. According to the above said Object.class is not directly through = = to judge it. The result should be false. Then you might as well open the string source.

public boolean equals (Object anobject) {
        if (this = = AnObject) {return
            true;
        }
        if (anobject instanceof string) {
            string anotherstring = (string) anobject;
            int n = value.length;
            if (n = = anotherString.value.length) {
                char v1[] = value;
                Char v2[] = Anotherstring.value;
                int i = 0;
                while (n--! = 0) {
                    if (V1[i]!= v2[i]) return
                        false;
                    i++;
                }
                return true;
            }
        return false;
    }

It is found that String.class gives an override of the Equals () method in Object.class, which equals () to determine whether the characters of two strings are all equal.
This is to modify the character of the S2 and then test again:

public static void Main (string[] args) {

        String S1 = "I am mobile 1";
        String s2 = new String ("I am mobile 2");

        System.out.println (S1==S2);
        System.out.println (s1.equals (S2));
    }

Run Result:
False
False

Results Analysis:
The Equals () method returns false because the S1 and S2 characters are not exactly the same

here, give the use of equals () and = = In practical applications: If two basic data types are compared, such as int a = 1,b = 2, and the comparison of a is equal to B. Use = = To compare member variables to determine whether two objects are equal (objects are not strings), such as the phone object that you write, to override the Equals () method inherited from the object class implementation. If you compare two strings, use the Equals () method directly.

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.