为什么我在我的java代码中获得下一个输出? (false true)
问题描述:
我认为输出应该是(true true)。对不起,我的英语为什么我在我的java代码中获得下一个输出? (false true)
public class A{
public static void main(String[] args) {
Integer i1 = 128;
Integer i2 = 128;
System.out.println(i1 == i2);
Integer i3 = 127;
Integer i4 = 127;
System.out.println(i3 == i4);
}
}
答
与原始int相反,整数是一个对象。您的比较是比较Integer类型的两个对象。我有点惊讶,你会得到“错误的真实”。如果你想尝试:
System.out.println(i1.intValue() == i2.intValue());
System.out.println(i3.intValue() == i4.intValue());
你应该得到预期的结果。
答
有Integer
实例的一个值的范围(至少-128 – 127)的高速缓存,当隐式转换的int
到Integer
时使用。
在这种情况下,128不在缓存中,因此代表该值的每个Integer
对象都是新的且不同的。
另一方面,值127,是保证在缓存中,因此重复获得Integer
的同一个实例。
你也应该阅读:http://stackoverflow.com/questions/1700081/why-does-128-128-return-false-but-127-127-return-true-when-converting-to-整合 – Eashi
这不回答这个问题。 – erickson