Почему list.get (0) .equals (null) не работает? - PullRequest
6 голосов
/ 01 апреля 2010

Первый индекс имеет значение 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 ]

6 голосов
/ 01 апреля 2010

Вы хотите:

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.

6 голосов
/ 01 апреля 2010

Я верю, что ты хочешь сделать это изменить,

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

до

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