java basics: What is the difference between == and the equals

==: its role is to determine the target address is not equal to two. That is, it is determined the objects are not the same object. (== basic data type is a value comparison, the comparison reference data type == memory address)

equals (): its role is to determine whether two objects are equal. But it is generally used in two cases:

Case 1: No cover class equals () method. Through equals () comparing two objects of the class, it is equivalent to the "==" to compare the two objects.

Case 2: class overrides equals () method. Generally, we cover the equals () method is equal to the contents of two objects; if their contents are equal, returns true (that is, the two objects are considered equal).
for example:

public class test1 {
    public static void main(String[] args) {
        String a = new String("ab"); // a 为一个引用
        String b = new String("ab"); // b为另一个引用,对象的内容一样
        String aa = "ab"; // 放在常量池中
        String bb = "ab"; // 从常量池中查找
        if (aa == bb) // true
            System.out.println("aa==bb");
        if (a == b) // false,非同一对象
            System.out.println("a==b");
        if (a.equals(b)) // true
            System.out.println("aEQb");
        if (42 == 42.0) { // true
            System.out.println("true");
        }
    }
}

Description:

String equals method is to be rewritten, because the object is the equals method to compare the memory address of the object, and the equals method of comparison is a value String object.
When you create an object of type String, the virtual find the same value as the object has no value already exists and you want to create in the constant pool, if you have put it assigned to the current reference. If not re-create a String object in the constant pool.

Published 438 original articles · won praise 2 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_37769323/article/details/104603188