Java-equals和“==”的区别

区别:

  “==” 是比较运算符,可以用于判断基本数据类型是否相等,当用于判断引用类型的时候,比较的对象的内存地址是否相同

  equals是Object类当中的方法,不可以用于判断基本数据是否相等,可以用于判断引用类型是否相等,但是子类通常会重写该方法,比较对象的属性值是否相等,比如  ( String,Integer)

 

举例说明

public class Test {
    public static void main(String[] args) {
        int num1 = 10;
        int num2 = 10;
        System.out.println(num1 == num2);   //true
        String str1 = "hello";
        String str2 = "hello";
        System.out.println(str1 == str1); //true
        String str3 = new String("hello");
        String str4 =  new String("hello");;
        System.out.println(str3 == str4); //false
        System.out.println(str3.equals(str4)); //true
    }
}

   运行结果说明:因为在常量池中,一个常量只会对应一个地址,因此不管是再多的 "abc", 这样的数据都只会存储一个地址. 所以所有他们的引用都是指向的同一块地址,因此基本数据类型和String常量是可以直接通过==来直接比较的。

  第一个:true,"=="可以用于基本数据类型的比较

  第二个:true,str1和str2都是存储了“hello”,而“hello”存在于字符串常量池当中,str1和str2指向的都是字符串常量池中同一个地址

  第三个:false,当使用new操作符的时候,在内存当中开辟空间,此时的str3和str4指向的是不同的内存空间地址

  第四个:true,String类型重写了equals方法,比较的是str3和str4中存储的值

 

posted @ 2022-11-01 00:38  通过程序看世界  阅读(36)  评论(0)    收藏  举报