Java自动装箱规则
我是一个java新手,并且对以下示例感到困惑。 是否可以认为“==”符号将比较Integers和int中的“autoboxed”整数之间的值,并比较整数之间的参考地址?
那么双打和0/0怎么样?
import edu.princeton.cs.introcs.*; public class Autoboxing { public static void cmp(Integer first, Integer second) { if (first < second) StdOut.printf("%d second) StdOut.printf("%d > %d\n", first, second); else StdOut.printf("%d and %d are incomparable\n", first, second); } public static void main(String[] args) { cmp(new Integer(42), 43); cmp(new Integer(42), new Integer(42)); cmp(43, 43); cmp(142, 142); Integer a0 = 1000; int b0 = 1000; Integer c0 = 1000; StdOut.println("a0==b0?" + (a0==b0)); StdOut.println("a0==c0?" + (a0==c0)); StdOut.println("b0==c0?" + (b0==c0)); double x1 = 0.0, y1 = -0.0; Double a1 = x1, b1 = y1; StdOut.println(x1 == y1); StdOut.println(a1.equals(b1)); double x2 = 0.0/0.0, y2 = 0.0/0.0; Double a2 = x2, b2 = y2; StdOut.println(x2 != y2); StdOut.println(!a2.equals(b2)); } }
结果是:
42 < 43 42 and 42 are incomparable 43 == 43 142 and 142 are incomparable ===== a0==b0?true a0==c0?false b0==c0?true ===== true false ===== true false
arithmetic operators
, comparison operators
出现时,拆箱将会出现问题。
例如:
Integer a = 10; a = a+10; //1.unboxing a to int 2.calculate a+10 3.boxing 20 to Integer. System.out.print(a > 10); //1.unboxing a to int 2. compare
但是当==
出现时,它取决于。
如果拳击类型出现在both side
,它将比较the reference
。但如果基本类型出现在one side
,而另一侧是拳击类型,拳击类型将unboxing
到基本类型。
例如:
Integer a = new Integer(129); Integer b = new Integer(129); System.out.println(a == b); // compare reference return false System.out.println(a == 129); // a will unboxing and compare 129 == 129 return true
PS:在Java.lang.Integer
Cache中,根据JLS的要求,支持-128和127(含)之间的值的自动装箱的对象标识语义。 请参阅源代码
所以:
Integer a = 127; Integer b = 127; //cached, the same as ba==b return ture Integer c = 129; Integer d = 129; // not cached, c==d return false
这是Autoboxing和Unboxing的教程。
您也可以通过JLS#5.1.7。 拳击转换和JLS#5.1.8。 拆箱转换
0.0 / 0.0
是NaN
,至少在数学中你无法比较infinity
。 我猜这就是为什么这种比较不起作用的原因。
来自JLS#4.2.3。 浮点类型,格式和值
正零和负零比较相等; 因此,表达式0.0 == – 0.0的结果为真,0.0> -0.0的结果为假
NaN是无序的,所以:
如果其中一个或两个操作数都是NaN(§15.20.1),则数值比较运算符<,<=,>和> =返回false。
如果任一操作数是NaN,则等于运算符==返回false。
特别是,如果x或y是NaN,则(x = y)将为假。
如果任一操作数是NaN(第15.21.1节),则不等式运算符!=返回true。
特别是,当且仅当x是NaN时,x!= x才为真。
如果检查Double#equals方法,则有两个例外
也有值true。 但是,有两个例外:
如果d1和d2都表示Double.NaN,则equals方法返回true,即使Double.NaN == Double.NaN的值为false。
如果d1表示+0.0而d2表示-0.0,反之亦然,则等值测试的值为false,即使+0.0 == – 0.0的值为true。
此定义允许哈希表正常运行。
==
只能用于检查变量是否相等,如果变量是基本类型的话。 对于对象变量, ==
用于比较对象的引用。 如果要比较对象的值,请使用.equals()
方法。
我不建议将盒装整数与==进行比较,因为它仅适用于某些值。
算术运算符,比较运算符将发生拆箱。