java - 整数包装对象仅在值 127 内共享相同的实例?

标签 java caching integer

这里它们是同一个实例:

Integer integer1 = 127;
Integer integer2 = 127;
System.out.println(integer1 == integer2);  // outputs "true"

但这里它们是不同的实例:

Integer integer1 = 128;
Integer integer2 = 128;
System.out.println(integer1 == integer2);  // outputs "false"

为什么包装对象只在值 127 内共享同一个实例?

最佳答案

因为它是由 Java 语言规范指定的。

JLS 5.1.7 Boxing Conversion :

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 r<sub>1</sub> and r<sub>2</sub> be the results of any two boxing conversions of p. It is always the case that r<sub>1</sub> == r<sub>2</sub>.

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 - 整数包装对象仅在值 127 内共享相同的实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5117132/

相关文章:

java - java.util.regex.Matcher.group 和字符串比较之间的不连续性

java - 尝试使用 java 中的线程写入图像时出现 FileNotFoundException

java - if else 语句

java - 如何在不使用 java.math.BigInteger 的情况下在 Java 中处理非常大的数字

c - 如何扫描值并忽略字符

java - 在java中使用纸张扫描仪需要哪些库?

java - 从 Guava RemovalListener 重新插入条目是否安全?

ruby - 应该如何测试 caches_page?

css - 我如何在公共(public)代理中缓存我用于标题的重图像(使用背景图像 :url css property in the stylesheet)

c# - 在 C# 中比较 2 个整数列表/数组的最佳方法是什么