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

Jes*_*ssy 7 java null list 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
    }
}
Run Code Online (Sandbox Code Playgroud)

Ant*_*ney 7

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

if(choice.get(0).equals(null))
Run Code Online (Sandbox Code Playgroud)

if(choice.get(0) == null))
Run Code Online (Sandbox Code Playgroud)


cle*_*tus 7

你要:

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
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

表达式choice.get(0).equals(null)应该抛出一个NullPointerException因为choice.get(0)null,你试着在它上面调用一个函数.因此,anyObject.equals(null)永远返回false.