• ==和equals()的区别


    1,equals()

     以下代码的执行结果分别为?

    1. public class Main {
    2. public static void main(String[] args) {
    3. String s1 = "hello world";
    4. String s2 = "hello world";
    5. String s3 = new String("hello world");
    6. String s4 = "hello"+" world";
    7. String s5 = "hello"+new String(" world");
    8. String s6 = "hello";
    9. String s7 = s6+" world";
    10. System.out.println(s1.equals(s2));
    11. System.out.println(s1.equals(s3));
    12. System.out.println(s1.equals(s4));
    13. System.out.println(s1.equals(s5));
    14. System.out.println(s1.equals(s7));
    15. }
    16. }

    以上输出结果均为true,原因如下:

    equals()只能用于引用类型之间,是在Object类中定义的,默认是比较地址,常常被重写来比较具体的属性值是否相同。String类重写了equals()来比较字符串的内容是否相同。 

    2,引用类型

    以下代码的执行结果分别为?

    1. public class Main {
    2. public static void main(String[] args) {
    3. String s1 = "hello world";
    4. String s2 = "hello world";
    5. String s3 = new String("hello world");
    6. String s4 = "hello"+" world";
    7. String s5 = "hello"+new String(" world");
    8. String s6 = "hello";
    9. String s7 = s6+" world";
    10. System.out.println(s1==s2);
    11. System.out.println(s1==s3);
    12. System.out.println(s1==s4);
    13. System.out.println(s1==s5);
    14. System.out.println(s1==s7);
    15. }
    16. }

     运行上述代码可知,s1==s2与s1==s4的结果为true,其他结果均为false。

    原因如下:

    由于String类型是引用数据类型而不是基本数据类型,因此此处==比较的是引用的地址是否相同。

    此处s1新建一个字面量对象"hello world"存储在堆中,并同时缓存到常量池中,因此s2直接复用常量池中的对象。因此利用二者地址相同,s1==s2的结果为true。

    s3在new String()的时侯会再创建一个字符串对象,并引用该字符串的内容,因此s3与s1的地址并不相同,因此s1==s3的结果返回false。同理s1==s5的结果也返回false。

    由于s4是使用两个字面量进行拼接,因此会直接复用常量池中的对象。因此s4的地址和s1的相同,因此s1==s4的结果返回true。

    又因为s6是一个变量,因此在所以在编译期并不会直接连接好,而是会创建一个新的对象存储hello world。因此s7与s1的地址并不相同,结果返回false。

    3,包装类

    以下代码的执行结果分别为?

    1. public class Main {
    2. public static void main(String[] args) {
    3. Integer i1 = 127;
    4. Integer i2 = 127;
    5. Integer i3 = 128;
    6. Integer i4 = 128;
    7. Integer i5 = new Integer(127);
    8. int i6 = 127;
    9. System.out.println(i1==i2);
    10. System.out.println(i3==i4);
    11. System.out.println(i1==i5);
    12. System.out.println(i1==i6);
    13. }
    14. }

    执行上述代码可知,i1==i2的结果为true,i3==i4的结果为false,i1==i5的结果为false,i1==i6的结果为true。

    原因如下:Integer.valueOf()会复用-128到127范围内的数据,因此范围在-128到127之间会返回true,即i1==i2的结果为true,i3==i4的结果为false。由于i5在new Integer()的时候会创建一个新的对象,因此i1和i5的地址并不相同,因此结果返回false。i6和i1进行==比较时,基本型封装型将会自动拆箱变为基本型后再进行比较,因此Integer()会自动拆箱为int类型再进行比较,因此返回true。

  • 相关阅读:
    .NET 6学习笔记(1)——通过FileStream实现不同进程对单一文件的同时读写
    物理层-数据链路层-网络层-传输层-会话层-表示层-应用层
    Allegro如何打盲埋孔操作指导
    服务器SMP、NUMA、MPP体系学习笔记。
    智能优化之遗传算法
    第1章丨IRIS Globals 简介
    React:通过嵌套对象循环
    图扑软件 3D 组态编辑器,低代码零代码构建数字孪生工厂
    C++14读写锁demo-读写操作都在子线程中
    云原生架构
  • 原文地址:https://blog.csdn.net/m0_61466268/article/details/126068616