Does java.util.List.isEmpty() check if the list itself is null? [duplicate] Ask Question

Does java.util.List.isEmpty() check if the list itself is null? [duplicate] Ask Question

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

For example:

List<String> test = null;

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

Will this throw a NullPointerException because test is null?

ベストアンサー1

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).

You may want to see this question.

おすすめ記事