为什么list.get(0).equals(null)不起作用?

时间:2010-03-31 22:39:55

标签: java list null arraylist

第一个索引设置为null(空),但它不打印正确的输出,为什么?

//set the first index as null and the rest as "High"
String a []= {null,"High","High","High","High","High"};

//add array to arraylist
ArrayList<Object> choice = new ArrayList<Object>(Arrays.asList(a)); 

for(int i=0; i<choice.size(); i++){
   if(i==0){
       if(choice.get(0).equals(null))
           System.out.println("I am empty");  //it doesn't print this output
    }
}

2 个答案:

答案 0 :(得分:6)

我相信你想做的就是改变,

if(choice.get(0).equals(null))

if(choice.get(0) == null))

答案 1 :(得分:6)

你想:

for (int i=0; i<choice.size(); i++) {
  if (i==0) {
    if (choice.get(0) == null) {
      System.out.println("I am empty");  //it doesn't print this output
    }
  }
}

表达式choice.get(0).equals(null)应抛出NullPointerException,因为choice.get(0)null,您尝试在其上调用函数。因此,anyObject.equals(null)始终返回false