为什么在java中比较两个MAX_值的整数失败?
我有以下几行Java代码:为什么在java中比较两个MAX_值的整数失败?,java,Java,我有以下几行Java代码: public class myProjects { public static void main(String[] args) { // TODO Auto-generated method stub Integer d = Integer.MAX_VALUE; Integer e = Integer.MAX_VALUE; System.out.println(d); System.out.println(e); i
public class myProjects {
public static void main(String[] args) {
// TODO Auto-generated method stub
Integer d = Integer.MAX_VALUE;
Integer e = Integer.MAX_VALUE;
System.out.println(d);
System.out.println(e);
if(d == e){
System.out.println("They are equal\n");
}else {
System.out.println("They are not equal\n");
}
}
}
Output:
2147483647
2147483647
They are not equal
即使它们具有相同的值,为什么它们也不相等?
整数。MAX\u value
返回一个int
。执行整数时,d=Integer.MAX_值
通过Integer.valueOf
将int
装箱为Integer
由于默认情况下缓存来自[-128127],valueOf
将为每个调用返回新实例。因此,它们不是相同的参考文献
您可以在生成的字节码中看到这一点:
public static void main(java.lang.String[]);
Code:
0: ldc #3 // int 2147483647
2: invokestatic #4 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
5: astore_1
6: ldc #3 // int 2147483647
8: invokestatic #4 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
以及整数的源代码。value of
:
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
公共静态整数值(int i){
如果(i>=IntegerCache.low&&i您正在比较对象,而不是原语
您应该使用d.equals(e);
而不是d==e
d==e
计算对象是否相同,它们是否相同。简单地说,整数是一个对象,而不是原语
值
要检查对象是否相等,需要使用equals
方法
e、 g
正如沙龙在评论中提到的那样
试着改变
Integer d = Integer.MAX_VALUE;
Integer e = Integer.MAX_VALUE;
到
看看会发生什么。这很有帮助。非常感谢
Integer d = Integer.MAX_VALUE;
Integer e = Integer.MAX_VALUE;
int d = Integer.MAX_VALUE;
int e = Integer.MAX_VALUE;