7

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
    }
}
Pyrolistical
  • 27,624
  • 21
  • 81
  • 106
Jessy
  • 15,321
  • 31
  • 83
  • 100
  • 1
    A trick: `System.out.println(Arrays.asList(null,"High","High","High","High","High"));` does what you want without all that extra code. I say its the "same" because you probably didn't know you could print nulls – Pyrolistical Mar 31 '10 at 22:46

2 Answers2

7

I believe what you want to do is change,

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

to

if(choice.get(0) == null))
Anthony Forloney
  • 90,123
  • 14
  • 117
  • 115
7

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
  • 616,129
  • 168
  • 910
  • 942