1. What is the difference between == and equals?

Use == to compare

  • 8 basic data types (byte, short, char, int, long, float, double, boolean) compare whether their values ​​are equal.
  • For reference data types, the comparison is whether their addresses in the heap memory are equal. Every time an object of reference type is new, the heap memory space will be reallocated, and the == comparison will return false.
package com.niuke.first;

public class Demo01 {
    
    
    public static void main(String[] args) {
    
    
        String s1 = "HelloWorld";
        String s2 = new String("HelloWorld");
        if (s1 == s2) {
    
    
            System.out.println("s1 == s2");
        } else {
    
    
            System.out.println("s1 != s2");
        }
        System.out.println(s1.hashCode());//439329280
        System.out.println(s2.hashCode());//439329280
        System.out.println(System.identityHashCode(s1));//608188624
        System.out.println(System.identityHashCode(s2));//1451270520
    }
}


  • Here you can see that the address values ​​​​of the two are different
  • identityHashCode(), whether rewritten or not, can see the address value
  • So the output s1 != s2

Compare using equals

  • The equals method is a method of the Object class, and all classes in Java inherit from the Object superclass.
  • The source code of the equals method of the JDK1.8 Object class is as follows, that is, the return result depends on the use == judgment result of the two objects.
 public static void main(String[] args) {
    
    
        String s1 = "HelloWorld";
        String s2 = new String("HelloWorld");
        if (s1.equals(s2)) {
    
    
            System.out.println("s1 equals s2");
        } else {
    
    
            System.out.println("s1 not equals s2");
        }

        System.out.println(s1.hashCode());//439329280
        System.out.println(s2.hashCode());//439329280
        System.out.println(System.identityHashCode(s1));//608188624
        System.out.println(System.identityHashCode(s2));//1451270520
    }
  • Here you can see that the address values ​​of the two are different, and the comparison is used at this time to compare the content
  • So the values ​​returned by both are equal

Guess you like

Origin blog.csdn.net/AzirBoDa/article/details/127071589