The difference between == and equals is

Before talking about the difference between equals and ==, let's briefly introduce the problem of memory allocation in the JVM.

The memory in the JVM is divided into stack memory and heap memory. What is the difference between the two?

When we create an object (new Object), its constructor is called to open up space, store the object data in heap memory, and at the same time generate corresponding references in stack memory, when we call in subsequent code When using the reference in the stack memory, it should be noted that the basic data type is stored in the stack memory. With a certain understanding, let's look at the difference between Equals and ==.



First of all, the biggest difference between equals and == is that one is a method and the other is an operator. In Java, both compare physical addresses rather than worth comparing.

Let's take an example to make it more intuitive.

Student student1 = new Student();

Student student2 = new Student();

System.out.println(student1.equals(student2));

System.out.println(student1 == student2);

No matter which method is used, the final result shows false , you may as well try it. why? It is because they are not comparing the value of the field in the object or the value of the object itself, but the physical address.

Let's take another example.

String a = new String("a");

String b = new String("a");

System.out.println(a == b);

System.out.println(a.equals(b));

When we create 2 String objects we will find that the result of execution is false true . Why is the value returned by euqals programmed with true this time? Because at this time the equals method not only compares the physical address but also compares the value,

The equals method in String is overridden. When the physical addresses are different, the values ​​are further compared. The code is as follows:

if(object instanceof String){}

Then the problem comes when I call

What is the result when System.out.println(student1.toString().equals(student2.toString()));

The result returned false . Why? This involves the problem of hashcode.

So is there any way to ensure that two objects compare equal? Presumably everyone has tried to override the equals method, and the final result is unsatisfactory. Why? Because just overriding the equals method does not change the hashcode value, the first comparison in java is the hashcode. So how did this problem come about?

You can try right->source->generate hashcode() and equals() to achieve this.


I'm still a rookie writing this for the first time, and there are many deficiencies. You can mention the bad parts, and you can correct the wrong places.

Guess you like

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