Why does list.get (0) .equals (null) not work?

The first index is set to null (empty), but it does not print the correct 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 } } 
+6
java arraylist list null
source share
2 answers

I believe that you want to change,

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

to

 if(choice.get(0) == null)) 
+6
source share

Do you want to:

 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 choice.get(0).equals(null) NullPointerException , because choice.get(0) is null , and you are trying to call a function on it. For this reason, anyObject.equals(null) will always return false .

+6
source share

All Articles