views:

103

answers:

2

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
    }
}
+5  A: 

I believe what you want to do is change,

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

to

if(choice.get(0) == null))
Anthony Forloney
Thank you :-) very much.
Jessy
No problem, see cletus' answer for a more in depth reason why it didn't work as expected.
Anthony Forloney
+2  A: 

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.

cletus
thank you very much :-)
Jessy
While returning true for `equals(null)` violates the API contract, it is in fact quite possible.
Michael Borgwardt