The difference between == and equals() in Java

About the difference between == and equals() in Java

==: operator

  • If you are comparing basic data type variables: compare whether the data saved by the two variables are equal. (Not necessarily the same type)
  • If the comparison is a reference data type variable: compare whether the address values ​​of the two objects are the same. That is, whether the two references point to the same object entity (Supplement: When using the == symbol, you must ensure that the variable types on the left and right sides of the symbol are the same).

equals(): a method in the Object class

  • The equals method in the underlying source code of the Object class: compares whether the address values ​​of two objects are the same. That is, whether the two references point to the same object entity
public boolean equals(Object obj) {
    
    
        return (this == obj);
    }
  • The classes in the JDK generally directly rewrite the equals method to compare whether the entity contents of two objects are equal (exceptions I haven't seen so far)
    For example, the String class:
public boolean equals(Object anObject) {
    
    
        if (this == anObject) {
    
    
            return true;
        }
        if (anObject instanceof String) {
    
    
            String aString = (String)anObject;
            if (!COMPACT_STRINGS || this.coder == aString.coder) {
    
    
                return StringLatin1.equals(value, aString.value);
            }
        }
        return false;
    }
  • If the equals method is used, the returned content depends on how the method is overridden in the corresponding class (or in its parent class) of the object calling this method. If there is no overriding, compare the address values ​​of the two objects for the same (The Object class in Java is the parent class of all classes).

Guess you like

Origin blog.csdn.net/m0_50654102/article/details/113888449