众所周知,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?
所有运算符对原始类型和原始包装类的执行是否相同?如果不是,那么哪些运算符子集可以同时处理基元及其对象包装器?
最佳答案
等式运算符(==
和 !=
)在处理包装类时不可靠。
首先,通常他们比较对象引用,而不是对象值。例如:
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
,后者又为 -128 到 127 之间的数字使用缓存 (IntegerCache
)。该实现负责对于这种奇怪的行为。
实际上,IntegerCache
类的实现允许在运行程序时通过属性 java.lang.Integer.IntegerCache.high
来配置上限。
这也适用于 Long
。
经验教训,你最好使用包装器的 equals()
方法。
其余的运算符应该可以工作,因为对象中的值在应用运算符之前会自动装箱。
关于java - 在 Java 中,运算符对原始类型和原始包装类的执行是否相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32236654/