是否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吗?
小智 101
我建议使用Apache Commons Collections
它实现了很好,并且记录良好:
/**
* 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)
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课程中.
在任何空引用上调用任何方法将始终导致异常.首先测试对象是否为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)
| 归档时间: |
|
| 查看次数: |
271455 次 |
| 最近记录: |