Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't list.get(0).equals(null) work?

The first index is set to null (empty), but it doesn't print the right output, why?

//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
    }
}
like image 913
Jessy Avatar asked Mar 31 '10 22:03

Jessy


2 Answers

I believe what you want to do is change,

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

to

if(choice.get(0) == null))
like image 124
Anthony Forloney Avatar answered Oct 19 '22 16:10

Anthony Forloney


You want:

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
    }
  }
}

The expression choice.get(0).equals(null) should throw a NullPointerException because choice.get(0) is null and you try and call a function on it. For this reason anyObject.equals(null) will always return false.

like image 44
cletus Avatar answered Oct 19 '22 17:10

cletus