gpt4 book ai didi

java - 使用新的与正常的减速和整数的性质来声明变量(装箱/拆箱)

转载 作者:行者123 更新时间:2023-12-02 07:39:58 27 4
gpt4 key购买 nike

大家可以向我解释一下 new 的性质以及 Integer 的使用

Integer i = new Integer(-10);
Integer j = new Integer(-10);
Integer k = -10;
Integer l=-10;
System.out.println(i==j);
System.out.println(k==l);

答案是假的

下一个

    Integer a=128;
Integer b=128;
Integer c=127;
Integer d=127;
System.out.println(a==b);
System.out.println(c==d);

我得到的答案是假的。谁能解释一下这种性质。预先感谢:)

最佳答案

在第一个示例中,您总是创建新的Integer对象并将这些引用分配给ij.对于kl,您使用的是自动装箱,它有时会创建新对象,而有时则不会。

在第二个示例中,您只是使用自动装箱 - 但具有不同的值,这演示了上面的“有时”。

来自section 5.1.7 of the JLS :

If the value p being boxed is true, false, a byte, or a char in the range \u0000 to \u007f, or an int or short number between -128 and 127 (inclusive), then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.

Ideally, boxing a given primitive value p, would always yield an identical reference. In practice, this may not be feasible using existing implementation techniques. The rules above are a pragmatic compromise. The final clause above requires that certain common values always be boxed into indistinguishable objects. The implementation may cache these, lazily or eagerly. For other values, this formulation disallows any assumptions about the identity of the boxed values on the programmer's part. This would allow (but not require) sharing of some or all of these references.

This ensures that in most common cases, the behavior will be the desired one, without imposing an undue performance penalty, especially on small devices. Less memory-limited implementations might, for example, cache all char and short values, as well as int and long values in the range of -32K to +32K.

关于java - 使用新的与正常的减速和整数的性质来声明变量(装箱/拆箱),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11736047/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com