整数比较值的输出错误 [英] Wrong output for integer comparison values

查看:163
本文介绍了整数比较值的输出错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码。

  public static void doIntCompareProcess(){
int a = 100;
int b = 100;

Integer c = 200;
Integer d = 200;

int f = 20000;
int e = 20000;

System.out.println(c == d);
compareInt(e,f);
compareInt(a,b);
}

public static void compareInt(Integer v1,Integer v2){
System.out.println(v1 == v2);
}

这给我这个输出:

  false 
false
true


$ b b

其中正确的输出应为:

  false 
false
false



>解决方案

最后一行对应于:

  compareInt(100,100) 

由于 compareInt()需要两个 Integer 对象,这两个参数自动加入。在此过程中,小于code> n 的实例 Integer(n) 。换句话说, compareInt()接收两个对同一个 Integer(100)对象的引用。这是导致最后一次比较评估为 true 的原因。



请参阅在Java中使用==运算符比较包装器对象



底线是不使用 == 运算符直接比较 Integer 对象。有关详情,请参阅 http://stackoverflow.com/a/1515811/367273


I have the following code.

public static void doIntCompareProcess() {
    int a = 100;
    int b = 100;

    Integer c = 200;
    Integer d = 200;

    int f = 20000;
    int e = 20000;

    System.out.println(c == d);
    compareInt(e, f);
    compareInt(a, b);
}

public static void compareInt(Integer v1, Integer v2) {
    System.out.println(v1 == v2);
}

That gives me this output:

false
false
true

Where the currect output should be:

false
false
false

Why am I getting the wrong output for the code?

解决方案

The last line corresponds to:

compareInt(100, 100);

Since compareInt() takes two Integer objects, the two parameters get auto-boxed. During that process, instances of Integer(n) for small values of n get interned. In other words, compareInt() receives two references to the same Integer(100) object. This is what's causing the last comparison to evaluate to true.

See Using == operator in Java to compare wrapper objects

The bottom line is to not use the == operator for directly comparing Integer objects. For further discussion, see http://stackoverflow.com/a/1515811/367273

这篇关于整数比较值的输出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆