java - 整数 i=3 vs 整数 i= 新整数 (3)

标签 java

<分区>

我正在比较 2 段代码。首先

Integer i=3;
Integer j=3;
if(i==j)
   System.out.println("i==j");  //prints i==j              

其次,

Integer i=3;
Integer j=new Integer(3);
if(i==j)
   System.out.println("i==j"); // does not print

我怀疑在第一个片段中为什么要打印 i==j ?引用不应该不同吗?

最佳答案

这与拳击的运作方式有关。来自JLS section 5.1.7 :

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.

基本上,Java 实现必须缓存适当小值的装箱表示,并且可以缓存更多。 == 运算符只是比较引用,所以它专门检测两个变量是否引用同一个对象。在第二个代码片段中,它们肯定不会,因为 new Integer(3) 绝对不是与之前创建的任何引用相同的引用...它总是创建一个新对象。

由于上述规则,此代码必须始终给出相同的结果:

Integer x = 127;
Integer y = 127;
System.out.println(x == y); // Guarantee to print true

然而这可能是两种方式:

Integer x = 128;
Integer y = 128;
System.out.println(x == y); // Might print true, might print false

关于java - 整数 i=3 vs 整数 i= 新整数 (3),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17494176/

相关文章:

java - 泛型扩展

java - 在 Google App Engine 托管的应用程序中解析 PDF 文件中的文本

java - Spark - 任务不可序列化 : How to work with complex map closures that call outside classes/objects?

java - 如何使用hibernate在spring中获取实体类中的inet

Java : Io exception: The Network Adapter could not establish the connection

java - 帮助简单的方法,Java

java - 使用 Apache Commons Daemon 从 Java 应用程序启动 Windows 服务时系统找不到指定的文件

java - 将 HashMap 从 Map<String, Boolean> 反转为 Map<Boolean, List<String>>

java - Spring 将 XML 数据文件注入(inject)到 Java 类

java - 在java中验证对象的最佳方法