gpt4 book ai didi

java - Java中奇怪的整数拳击

转载 作者:IT老高 更新时间:2023-10-28 11:23:20 26 4
gpt4 key购买 nike

我刚刚看到类似这样的代码:

public class Scratch
{
public static void main(String[] args)
{
Integer a = 1000, b = 1000;
System.out.println(a == b);

Integer c = 100, d = 100;
System.out.println(c == d);
}
}

运行时,这段代码会打印出来:

false
true

我明白为什么第一个是false:因为这两个对象是独立的对象,所以==比较引用。但我想不通,为什么第二个语句返回 true?当整数的值在一定范围内时,是否会出现一些奇怪的自动装箱规则?这是怎么回事?

最佳答案

true 行实际上是由语言规范保证的。来自 section 5.1.7 :

If the value p being boxed is true, false, a byte, a char in the range \u0000 to \u007f, or an int or short number between -128 and 127, 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 characters and shorts, as well as integers and longs in the range of -32K - +32K.

关于java - Java中奇怪的整数拳击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3130311/

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