akram akram - 3 months ago 14
Java Question

Does java.util.List.isEmpty() check if the list itself is null?

Does

java.util.List.isEmpty()
check if the list itself is
null
, or do I have to do this check myself?

For example:

List test = null;

if(!test.isEmpty()) {
for(Object o : test) {
// do stuff here
}
}


Will this throw a
NullPointerException
because test is
null
?

Answer

You're trying to call the isEmpty() method on a null reference (as List test = null; ). This will surely throw a NullPointerException. You should do if(test!=null) instead (Checking for null first).

The method isEmpty() returns true, if an ArrayList object contains no elements; false otherwise (for that the List must first be instantiated that is in your case is null).

Edit:

You may want to see this question.