当我比较ArrayList的两个元素时,会发生非常有线的事情

时间:2016-01-27 08:02:17

标签: java arraylist

public static void main(String[] args) {
    ArrayList<Integer> myList = new ArrayList<Integer>();
    myList.add(2000);
    myList.add(2000);
    myList.add(2);
    myList.add(2);

    if(myList.get(1)==myList.get(0))System.out.println("2000 equal check");
    if(myList.get(1)!=myList.get(0))System.out.println("2000 not equal check");
    if(myList.get(2)==myList.get(3))System.out.println("2 equal check");
    if(myList.get(2)!=myList.get(3))System.out.println("2 not equal check");
}

我的代码如上所示。结果如下所示。

2000不等于检查

2等同检查

The results show me very wired things..

我真的很困惑......如果有人可以帮我这件事我很感激。

2 个答案:

答案 0 :(得分:2)

您不得使用==来比较引用类型(任何对象)。始终使用equals()。

如果两个Object引用指向内存中的相同对象,则

==返回true。

鉴于此,问题在于Integer对象是如何形成的:

在处理源代码时,编译器会执行不同的操作 添加(2000)并添加(2):

对于介于-127和128之间的值...编译器实际上不会创建新的Integer对象,而是执行一些“智能”缓存...所以add(2)总是添加SAME对象实例。

因此使用==的引用相等性检查返回true。对于add(2000),每次都返回一个新对象;因此==返回false。

答案 1 :(得分:1)

您正在使用Integer个对象,因此,您应该使用.equals()

if(myList.get(1).equals(myList.get(0)))
     System.out.println("2000 equal check");
if(!myList.get(1).equals(myList.get(0)))
     System.out.println("2000 not equal check");
// works because of: see link in the comments to your question
if(myList.get(2)==myList.get(3))System.out.println("2 equal check");
if(myList.get(2)!=myList.get(3))System.out.println("2 not equal check");

The link from the comment section of your question.