Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vue.js/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么在java中比较两个MAX_值的整数失败?_Java - Fatal编程技术网

为什么在java中比较两个MAX_值的整数失败?

为什么在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

我有以下几行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);
    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;