• 陷阱:使用==来比较原始的包装器对象,如Integer


    陷阱:使用==来比较原始的包装器对象,如 Integer49
    (这一缺陷同样适用于所有的原始包装类,但我们会说明它Integer和int。)

    使用Integer对象时,使用它==来比较值是很诱人的,因为这是您将使用的int值。在某些情况下,这似乎有效:

    
    Integer int1_1 = Integer.valueOf("1");
    Integer int1_2 = Integer.valueOf(1);
    
    System.out.println("int1_1 == int1_2: " + (int1_1 == int1_2));          // true
    System.out.println("int1_1 equals int1_2: " + int1_1.equals(int1_2));   // true
    
    

    在这里我们创建了两个Integer具有值的对象,1并比较它们(在这种情况下,我们创建了一个来自一个String,一个来自一个int文字,还有其他的选择)。此外,我们观察到两种比较方法(==和equals)都产生true。

    当我们选择不同的值时,这种行为会发生变化:

    
    Integer int2_1 = Integer.valueOf("1000");
    Integer int2_2 = Integer.valueOf(1000);
    System.out.println("int2_1 == int2_2: " + (int2_1 == int2_2));  //false
    System.out.println("int2_1 equals int2_2: " + int2_1.equals(int2_2)); // true
    
    

    在这种情况下,只有比较equals才能得到正确的结果。

    这种行为差异的原因是,JVM维护Integer范围为-128到127 的对象的缓存(可以使用系统属性“java.lang.Integer.IntegerCache.high”或JVM来覆盖上限值参数“-XX:AutoBoxCacheMax = size”)。对于此范围内的值,Integer.valueOf()将返回缓存的值,而不是创建一个新的值。

    因此,在第一个示例中,Integer.valueOf(1)并且Integer.valueOf(“1”)调用返回相同的缓存Integer实例。相比之下,在第二个示例中Integer.valueOf(1000),Integer.valueOf(“1000”)创建并返回了新Integer对象。

    ==参考类型的运算符测试参考相等(即同一对象)。
    因此,
    在第一个例子中int1_1 == int2_1是true因为引用是相同的。
    第二个例子int2_1 == int2_2是false,因为引用是不同的。

  • 相关阅读:
    面向对象中一些容易混淆的概念
    day12作业
    day10作业
    day09作业
    Where与Having的区别
    排序算法之快速排序
    排序算法之冒泡排序
    jQuery中的100个技巧
    用node.js给图片加水印
    代码高亮美化插件-----SyntaxHighlighter
  • 原文地址:https://www.cnblogs.com/jimloveq/p/10609491.html
Copyright © 2020-2023  润新知