fas*_*ava 164 java syntax loops for-loop
在Java中的for循环中防止null的最佳方法是什么?
这看起来很难看:
if (someList != null) {
for (Object object : someList) {
// do whatever
}
}
Run Code Online (Sandbox Code Playgroud)
要么
if (someList == null) {
return; // Or throw ex
}
for (Object object : someList) {
// do whatever
}
Run Code Online (Sandbox Code Playgroud)
可能没有任何其他方式.他们应该把它放在for构造本身,如果它是null,那么不要运行循环?
Osc*_*Ryz 219
您应该更好地验证从哪里获得该列表.
您只需要一个空列表,因为空列表不会失败.
如果你从其他地方得到这个列表并且不知道它是否正常你可以创建一个实用工具方法并像这样使用它:
for( Object o : safe( list ) ) {
// do whatever
}
Run Code Online (Sandbox Code Playgroud)
当然safe会是:
public static List safe( List other ) {
return other == null ? Collections.EMPTY_LIST : other;
}
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 99
如果传入null,您可能会编写一个返回空序列的辅助方法:
public static <T> Iterable<T> emptyIfNull(Iterable<T> iterable) {
return iterable == null ? Collections.<T>emptyList() : iterable;
}
Run Code Online (Sandbox Code Playgroud)
然后使用:
for (Object object : emptyIfNull(someList)) {
}
Run Code Online (Sandbox Code Playgroud)
我不认为我实际上是这样做的 - 我通常会使用你的第二种形式.特别是,"或者抛出ex"很重要 - 如果它真的不应该为null,那么你肯定应该抛出异常.你知道出了什么问题,但是你不知道损坏的程度.早点中止.
Fre*_*Pym 27
它已经是2017年了,您现在可以使用Apache Commons Collections4
用法:
for(Object obj : ListUtils.emptyIfNull(list1)){
// Do your stuff
}
Run Code Online (Sandbox Code Playgroud)
您可以对其他Collection类执行相同的空安全检查CollectionUtils.emptyIfNull.
使用Java 8 Optional:
for (Object object : Optional.ofNullable(someList).orElse(Collections.emptyList())) {
// do whatever
}
Run Code Online (Sandbox Code Playgroud)
如果List从实现的方法调用中获取,则不返回null,返回空List.
如果您无法更改实施,那么您将无法进行null检查.如果它不应该null,那么抛出异常.
我不会去寻找一个返回空列表的辅助方法,因为它可能有用一段时间,但是你会习惯在你可能隐藏一些错误的每个循环中调用它.
使用ArrayUtils.nullToEmpty来自commons-lang于阵列库
for( Object o : ArrayUtils.nullToEmpty(list) ) {
// do whatever
}
Run Code Online (Sandbox Code Playgroud)
此功能存在于commons-lang库中,该库包含在大多数Java项目中.
// ArrayUtils.nullToEmpty source code
public static Object[] nullToEmpty(final Object[] array) {
if (isEmpty(array)) {
return EMPTY_OBJECT_ARRAY;
}
return array;
}
// ArrayUtils.isEmpty source code
public static boolean isEmpty(final Object[] array) {
return array == null || array.length == 0;
}
Run Code Online (Sandbox Code Playgroud)
这是相同的,通过@OscarRyz给出了答案,但对于着想干的口头禅,我相信这是值得注意的.请参阅commons-lang项目页面.这是nullToEmptyAPI 文档和源代码
Maven条目包含commons-lang在您的项目中(如果尚未包含).
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)
遗憾的是,commons-lang不为List类型提供此功能.在这种情况下,您必须使用前面提到的辅助方法.
public static <E> List<E> nullToEmpty(List<E> list)
{
if(list == null || list.isEmpty())
{
return Collections.emptyList();
}
return list;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
151378 次 |
| 最近记录: |