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

新手上路,请多包涵

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

例如:

 List<String> test = null;

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

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

原文由 K‘’ 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 680
2 个回答

您正在尝试在 null 参考上调用 isEmpty() 方法(如 List test = null; )。这肯定会抛出 NullPointerException 。您应该改为执行 if(test!=null) (首先检查 null )。

方法 isEmpty() 返回true,如果 ArrayList 对象不包含元素;否则为假(因为 List 必须首先实例化,在你的情况下是 null )。

你可能想看看 这个问题

原文由 Lion 发布,翻译遵循 CC BY-SA 4.0 许可协议

我建议使用 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());
}

原文由 cschaefer 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题