Check list empty Java

Does java.util.List.isEmpty[] check if the list itself is null?

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.


I would recommend using Apache Commons Collections

//commons.apache.org/proper/commons-collections/javadocs/api-release/org/apache/commons/collections4/CollectionUtils.html#isEmpty[java.util.Collection]

which implements it quite ok and well documented:

/** * Null-safe check if the specified collection is empty. *

* Null returns true. * * @param coll the collection to check, may be null * @return true if empty or null * @since Commons Collections 3.2 */ public static boolean isEmpty[Collection coll] { return [coll == null || coll.isEmpty[]]; }

This will throw a NullPointerException - as will any attempt to invoke an instance method on a null reference - but in cases like this you should make an explicit check against null:

if [[test != null] && !test.isEmpty[]]

This is much better, and clearer, than propagating an Exception.

Video liên quan

Chủ Đề