The difference between java.equals() and ==

(1) Compare basic data types

For the variables of the 8 basic data types, the variable directly stores the "value", so when the relational operator == is used for comparison, the "value" itself is compared.

(2) Compare wrapper classes

public class Main {
    public static void main(String[] args) {
        Integer i1 = new Integer(1);
        Integer i2 = new Integer(1);
        System.out.println(i1 == i2);//false
        System.out.println(i1.equals(i2));//true
    }
}

Here "==" compares the memory address pointed to by the variable. The addresses stored by two different objects generated by new are different. The "equals" here compares the content. Why is the content compared here, because Integer overrides the equals method. Attach the source code:

 

    public boolean equals(Object obj) {
        if (obj instanceof Integer) {
            return value == ((Integer) obj).intValue();
        }
        return false;
    }

 

(3) Compare String

"==" compares the memory address, "equals" compares the value, String overrides the equals method. Source code:

 

    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;
    }

 

(4) Comparison object

public class Main {
    public static void main(String[] args) {
        Test t1 = new Test();
        Test t2 = new Test();
        System.out.println(t1 == t2);//false
        System.out.println(t1.equals(t2));//false
    }
}

Classes that do not override the equals method call the equals method of Object:

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

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325070173&siteId=291194637
Recommended