【问题标题】:In Java, do operators perform identically on primitive types and primitive wrapper classes?在 Java 中,运算符对原始类型和原始包装类的执行是否相同?
【发布时间】:2015-08-26 21:03:37
【问题描述】:

众所周知,Java 中的原语有数学和逻辑运算符,您可以对它们使用。我的问题是相同的操作逻辑是否适用于他们的表亲,原始包装类。

Integer a = new Integer(2);
Integer b = new Integer(2);

Integer c = a * b;  //Does c.integerValue() returns 4?
boolean d = a == b; //Is d true? 
Integer e = a | c;  //Does e.integerValue() return 6?
Integer f = c % a;  //Does f.integerValue() return 0?
a++;                //Does a.integerValue() return 3?

所有运算符对原始类型和原始包装类的执行是否相同?如果不是,哪些运算符子集同时适用于原语及其对象包装器?

【问题讨论】:

  • 为什么这被否决了?

标签: java object operators primitive


【解决方案1】:

等式运算符(==!=)在使用包装类时不可靠。

首先,它们通常比较对象引用,而不是对象值。例如:

Integer a = new Integer(24);
Integer b = new Integer(24);
System.out.println(a == b); // Prints false
System.out.println(a != b); // Prints true

其次,包装类的创建方式很重要,例如:

Integer a = 24;
Integer b = 24;
System.out.println(a == b); // Prints true
System.out.println(a != b); // Prints false

在这种情况下,当取消装箱时,Integer 使用 Integer.valueOf,而后者又使用缓存 (IntegerCache) 来存储 -128 到 127 之间的数字。该实现是造成这种奇怪行为的原因。

实际上,IntegerCache 类的实现允许您在运行程序时通过属性java.lang.Integer.IntegerCache.high 配置上限。

这也适用于Long

经验教训,你最好使用带有包装器的equals() 方法。

其余的运算符应该可以工作,因为对象中的值在应用运算符之前已自动装箱。

【讨论】:

  • 正是我正在寻找的答案!我知道 java 使用对象引用进行相等计算,但我不知道用硬编码值初始化包装器会导致相等运算符按预期执行。
【解决方案2】:

不,特别是 ==!= 比较参考。

这意味着new Integer(1) != new Integer(1)

其他操作基本相同。

【讨论】:

    【解决方案3】:

    除了上面给出的答案,我想添加以下内容: 对包装类型进行数学运算时要小心。因为你可以得到NullPointerException。考虑这个例子:

        Double a = 5.0;
        Double b = null;
    
        System.out.println(a + b);
    

    【讨论】:

      猜你喜欢
      • 2018-06-26
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-11
      • 1970-01-01
      相关资源
      最近更新 更多