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
}
}
I believe what you want to do is change,
if(choice.get(0).equals(null))
to
if(choice.get(0) == null))
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With