当值超过150时,Int值不相等?

时间:2013-01-15 23:58:02

标签: java autoboxing

代码看起来像

public void option() {
    seeTasks = tasks.getTasks();
        for (int i = 0; i < seeTasks.size(); i++) {
            for (int b = 0; b < seeBoxes.size(); b++) {
               System.out.println("see Tasks: " + seeTasks.get(i) + 
                           " see Boxes " + seeBoxes.get(b));
            if(seeTasks.get(i) == seeBoxes.get(b)) {
                option.add(seeTasks.get(i));
            }
        }
    }
    System.out.println(option);
}

如果if的值低于150,则seeTaks.get(i) seeTasks.get(i)语句将不会通过。这怎么可能?如下所示,370不包括在内。如果我将110更改为150,则不会通过。

println的输出是:

see Tasks: 50 see Boxes 50
see Tasks: 50 see Boxes 110
see Tasks: 50 see Boxes 150
see Tasks: 50 see Boxes 210
see Tasks: 50 see Boxes 270
see Tasks: 50 see Boxes 310
see Tasks: 50 see Boxes 370
see Tasks: 50 see Boxes 430
see Tasks: 110 see Boxes 50 
see Tasks: 110 see Boxes 110
see Tasks: 110 see Boxes 150
see Tasks: 110 see Boxes 210
see Tasks: 110 see Boxes 270
see Tasks: 110 see Boxes 310
see Tasks: 110 see Boxes 370
see Tasks: 110 see Boxes 430
see Tasks: 370 see Boxes 50
see Tasks: 370 see Boxes 110
see Tasks: 370 see Boxes 150
see Tasks: 370 see Boxes 210
see Tasks: 370 see Boxes 270
see Tasks: 370 see Boxes 310
see Tasks: 370 see Boxes 370
see Tasks: 370 see Boxes 430
[50, 110]

1 个答案:

答案 0 :(得分:5)

我怀疑

seeTasks.get(i)

seeBoxes.get(b)

都返回Integer。然后,对于低于128的值,Integer高速缓存返回相同的实例,但对于较大的值,则返回新实例。使用equals()