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

K''*_*K'' 96 java list

是否java.util.List.isEmpty()检查清单本身null,或做我必须做这个检查自己?

例如:

List<String> test = null;

if (!test.isEmpty()) {
    for (String o : test) {
        // do stuff here            
    }
}
Run Code Online (Sandbox Code Playgroud)

这会抛出NullPointerException因为测试null吗?

Lio*_*ion 111

您正尝试isEmpty()null引用(as List test = null; )上调用该方法.这肯定会抛出一个NullPointerException.你应该做if(test!=null)(而不是null先检查).

isEmpty()如果ArrayList对象不包含任何元素,则该方法返回true ; 否则为false(因为List必须首先实例化,在您的情况下null).

编辑:

您可能想看到这个问题.


小智 101

我建议使用Apache Commons Collections

http://commons.apache.org/proper/commons-collections/javadocs/api-release/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());
}
Run Code Online (Sandbox Code Playgroud)

  • 即使这个问题不是特别聪明,我还是进去寻找这样的答案。 (3认同)
  • Apache Utills 非常棒!最近我发现了 SpringUtils.join - 在集合上使用非常有用。对不起,有点不对劲:) (2认同)

pb2*_*b2q 17

抛出NullPointerException- 就像在null引用上调用实例方法的任何尝试一样 - 但在这种情况下,您应该对以下内容进行显式检查null:

if ((test != null) && !test.isEmpty())
Run Code Online (Sandbox Code Playgroud)

这比传播更好,更清晰Exception.


Abd*_*han 10

java.util.List.isEmpty()不检查列表是否为空.

如果您使用的是Spring框架,则可以使用null该类检查列表是否为空.它还负责CollectionUtils参考.以下是Spring框架null类的代码片段.

public static boolean isEmpty(Collection<?> collection) {
    return (collection == null || collection.isEmpty());
}
Run Code Online (Sandbox Code Playgroud)

即使您没有使用Spring,也可以继续调整此代码以添加到您的CollectionUtils课程中.


cdh*_*wie 7

在任何空引用上调用任何方法将始终导致异常.首先测试对象是否为null:

List<Object> test = null;
if (test != null && !test.isEmpty()) {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

或者,编写一个方法来封装这个逻辑:

public static <T> boolean IsNullOrEmpty(Collection<T> list) {
    return list == null || list.isEmpty();
}
Run Code Online (Sandbox Code Playgroud)

然后你可以这样做:

List<Object> test = null;
if (!IsNullOrEmpty(test)) {
    // ...
}
Run Code Online (Sandbox Code Playgroud)


lxk*_*vlk 7

除了Lion的回答,我可以说你更好用if(CollectionUtils.isNotEmpty(test)){...}

这也会检查 null,因此不需要手动检查。