java.util.List.isEmpty() 是否检查列表本身是否为空?

2022-08-31 08:07:16

检查列表本身是 ,还是我必须自己进行此检查?java.util.List.isEmpty()null

例如:

List<String> test = null;

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

这会抛出一个因为测试是?NullPointerExceptionnull


答案 1

您正在尝试在引用上调用该方法(如 )。这肯定会抛出一个.您应该改用(首先检查)。isEmpty()nullList test = null;NullPointerExceptionif(test!=null)null

如果对象不包含任何元素,则该方法返回 true;否则为 false(因为在您的案例中,必须首先实例化 )。isEmpty()ArrayListListnull

您可能希望看到此问题


答案 2

我建议使用Apache Commons Collections:

https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/CollectionUtils.html#isEmpty-java.util.Collection-

这实现了它相当好,并且有据可查:

/**
 * Null-safe check if the specified collection is empty.
 * <p>
 * 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());
}