"==" and "equals" are sometimes not what you think

We all know that when comparing two objects with "==", the addresses of both are compared. And "equals" compares the values ​​of both of them when comparing.

But today I will tell you something that refreshes the Three Views.
		StringBuffer a=new StringBuffer("a");
        StringBuffer b=new StringBuffer("a");
        System.out.println(a==b);//false
        System.out.println(a.equals(b));//false
        String c=new String("a");
        String d=new String("a");
        System.out.println(c==d);//false
        System.out.println(c.equals(d));//true

If we new an object, it will be assigned an address in the memory, so as long as the new object compares their addresses, the result is false, but equals compares the value, so why a.equals(b) gets The result is false, and c.equals(d) gets true?

This requires us to look at the source code and jdk
The equals method is overridden under the String package

insert image description here
insert image description here
This is the source code of equals in String
insert image description here

The equals method under the String package is not overridden, but the equals method is inherited from objec

insert image description here
insert image description here
Because there is no method to override equals in StringBuffer, it still compares the addresses of two objects, but the equals method inherited from the parent class in String is overridden, and the value of the two objects is compared after rewriting.

Everyone is looking at this piece of code
		class Demo1{}
		
		Demo1 a=new Demo1();
        Demo1 b=new Demo1();
        System.out.println(a.equals(b));//false
        System.out.println(a==b);//false
        a=b;
        System.out.println(a.equals(b));//true
        System.out.println(a==b);//true

For non-string variables, "==" and "equals" are used to compare their first addresses in the heap memory, so the first two prints are false, and they are printed after letting a point to the address of b. is two true.

[1]https://wenku.baidu.com/view/008b31e2f12d2af90342e667.html

Guess you like

Origin blog.csdn.net/MCYZSF/article/details/89914955