Differences in Java "==" and equals () of

Analyzing equal symbol "=="

"==" symbol is determined equal to the basic data for comparison and reference types of data. When comparing the basic data types when the comparison value is, when comparing the comparison reference data type is a reference (pointer).

"==" basic types of data

Basic data type refers to the eight data types in Java: byte, short, int, long, float, double, char, boolean.

These eight basic data types have a common feature is that they are specific values ​​in memory, such as a type of int data "2", which is stored in the form of a machine 0000 0010 8-bit data bus. (8 machines hypothetical)

== When comparing two basic types of data when the time is in comparison to their respective values ​​in memory.

In order to take care of the students to be inquisitive, and then add the two values ​​is how to compare: cpu for the difference in the time to compare the two values ​​will then see the flag register. Flag register stores the result of the operation, which has a flag bit is zero, and if the bit is 1, demonstrate difference between the two is zero, the two are equal.

"==" Analyzing the data reference type

Reference data types is well understood literally, it is a reference to the heap memory of a specific object.

For example, Student stu = new Student(); stu here is a reference, it points out that the current new Student  object. When we want to operate the Student  object, the only reference to the operation, for example .  int age = stu.getAge();

Therefore, with the "==" Analyzing two types of reference data are equal when actually determining two reference points to the same object .

See the following example:

public static void main(String[] args) {
    String s1 = "hello";    //s1指向字符串常量池中的"hello"字符串对象
    String s2 = "hello";    //s2也指向字符串常量池中的"hello"字符串对象
    System.out.println(s1 == s2);   //true

    String s3 = new String("hello");   //s3指向的是堆内存中的字符串对象 
    System.out.println(s1 == s3);    //false
}


Can be seen from the above example, since the reference to "hello" string "s1" and "s2" are pointed constant pool, it returns true. (I'll publish a detailed article about Java strings, involving initialization string and string constant pool of knowledge, etc.)

And "s3" points to the newly created string object, as long as the use of the newkeyword in the heap memory will create a new object.

That point s1 and s3 are different string object, it returns false.

 

The method of determination equal equals ()

equals () and Java custom comparison == essentially different, == can be seen as the encapsulation of "comparative data means the operating system", and equals () is each object comes with the comparative method, it is rule.

equals () and == essential difference between the more popular argument is: == comparison rules are scheduled to die, that is, the value of comparing two data.

The equals () comparison rules are not fixed, it can be defined by the user.

See the examples below:

public static void main(String[] args) {
    String s1 = "hello";
    String s3 = new String("hello");    
    System.out.println(s1.equals(s3));    //true
}

Recall that the foregoing case: when == comparison with the above s1 and s3 of the comparison result is false. And when () the comparison with equals, the result is true.

Want to know why we have to see the source code, the following is the String class equals () method of the source code.

public boolean equals(Object anObject) {
    if (this == anObject) {    //先比较两个字符串的引用是否相等(是否指向同一个对象), 是直接返回true
        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;
}

The source can be seen from the above, when equals () method is called when the data is of type String, reference is first determined whether the two strings are equal, that is to say two string reference point to the same object, it returns true .

If it is not pointing to the same object, you put the two characters in the string to compare one by one. Since s1 and s3 are the string "hello", is a successful match, the final return true.

Question: Why design equals () method?

Through the above explanation, I believe you already know the difference between == and the equals () in the: a comparison rules are scheduled to die, one by the programmer can define your own.

But why have equals () method, but also can be customized freedom?

The core of this issue to fall into the Java language - an object-oriented thinking.

Java is different from the process-oriented C language, Java is an object-oriented high-level language. If the process-oriented programming, data is stored directly on the memory operation, then, with the defined rules == determines whether the two data are equal sufficient.

And all things are objects in Java, we often have to face the question is whether these two objects are equal, but not the two strings of binary numbers are equal, only == is totally not enough.

Since Java programmers to create a variety of objects to meet their business needs, the system can not know in advance the conditions under which the two objects considered equal, Java powers simply to determine whether the object is equal to the programmer .

Specific measures are: All classes must inherit the Object class, and written in Object class equals () method. Programmers can compare to realize their strategy by overriding the equals () method, you can not rewrite, the use of equals Object class () comparing policies.

//Object类中的equals()方法源码
public boolean equals(Object obj) {
    return (this == obj);
}

() Can be seen from the source equals Object class, if the programmer does not explicitly override equals () method, the default comparing whether two objects point to the same reference.

Added: Comparing the basic data types of packaging

Since that everything in Java objects, and even the basic data types have their corresponding wrapper class, what their corresponding comparison strategy is it?

public static void main(String[] args) {
    int a = 3;
    Integer b = new Integer(3);
    System.out.println(b.equals(a));    //true, 自动装箱
}

From the above code can be seen that although the two different references, but the results still output true, proof packaging Integer class overrides the equals () method, track their source:

//Integer类中的equals方法
public boolean equals(Object obj) {
    if (obj instanceof Integer) {
        return value == ((Integer)obj).intValue();
    }
    return false;
}

Seen from the source, after rewriting the equals (), or the comparison value of the basic data types of the basic types of packaging.

 

No public sharing of knowledge sources "Geeks Java technology"   

Guess you like

Origin www.cnblogs.com/lingchendujing/p/11095635.html