The difference between "==" and "equals()" in Java

  • “==”
    • 1. It can be used in basic data type variables and reference data type variables
    • 2. If comparing variables of basic data types: compare whether the data saved by the two variables are equal. (The types do not have to be the same and the Boolean types cannot be compared)
    • 3. 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
        int i=10;
        int j=10;
        double k=10.0;
        char m = 10;
        char a = 'A';
        String a1=new String("a1");
        String a2=new String("a1");
        System.out.println(a==65);//true
        System.out.println(i==j);//true
        System.out.println(i==k);//true(int自动转化为double类型)
        System.out.println(m == i);//true
        System.out.println(a1 == a2);//false
  • “equals()”
    • 1. Is a method, not an operator
    • 2. Only applicable to reference data types

Object类中equals()的定义:
public boolean equals(Object obj) {
    
    
	        return (this == obj);
}
  • 3. The equals() and == defined in the Object class have the same effect: compare whether the address values ​​of two objects are the same. That is, whether the two references point to the same object entity
  • 4. The equals() method in the Object class is rewritten like String, Date, File, and wrapper classes. After rewriting, the comparison is not whether the addresses of the two references are the same, but whether the "entity content" of the two objects is the same.
  • 5. Normally, if our custom class uses equals(), it usually compares whether the "entity content" of two objects is the same. Then, we need to rewrite equals() in the Object class.
  • 6. The principle of rewriting: compare whether the entity content of two objects is the same.

Guess you like

Origin blog.csdn.net/dwjdj/article/details/113106313