检测空引用数组中的 [英] Detect null reference in an array
问题描述
欲检测的阵列的子范围是否包含空引用。不知怎的,像这样的:
公共静态< T>布尔containsNull
(T []数组,INT fromInclusive,INT toExclusive)
{
的for(int i = fromInclusive; I< toExclusive ++ I)
{
如果(数组[我] == NULL)返回true;
}
返回false;
}
有没有这样的方法在Java库,所以我不必手动遍历数组?也许我已经被宠坏了C ++的出色支持算法集中code,在那里我可以只写:
的#include<算法>
布尔found_null =(标准::找到(阵列+从,阵+到,0)=阵列+到!);
检查是否 Arrays.asList(myarray的)。载(空)
。
要检查阵列的一部分,检查是否
Arrays.asList(myarray的).subList(从,到)。载(空)
这不会创建数组的不必要的副本;无论 asList
和子列表
创建<一个href="http://www.grep$c$c.com/file/repository.grep$c$c.com/java/root/jdk/openjdk/6-b14/java/util/Arrays.java#Arrays.ArrayList"><$c$c>ArrayList$c$c>和<一href="http://www.grep$c$c.com/file/repository.grep$c$c.com/java/root/jdk/openjdk/6-b14/java/util/AbstractList.java#RandomAccessSubList"><$c$c>RandomAccessSubList$c$c>对象包装了原始的阵列,而不复制它。
I want to detect whether or not a subrange of an array contains the null reference. Somehow like this:
public static <T> boolean containsNull
(T[] array, int fromInclusive, int toExclusive)
{
for (int i = fromInclusive; i < toExclusive; ++i)
{
if (array[i] == null) return true;
}
return false;
}
Is there a method like this in the Java library so I don't have to manually loop over the array? Maybe I have been spoiled by C++'s excellent support for algorithmically focused code, where I can just write:
#include <algorithm>
bool found_null = (std::find(array + from, array + to, 0) != array + to);
Check whether Arrays.asList(myArray).contains(null)
.
To check part of an array, check whether
Arrays.asList(myArray).subList(from, to).contains(null)
This will not create unnecessary copies of the array; both asList
and subList
create ArrayList
and RandomAccessSubList
objects that wrap the original array without copying it.
这篇关于检测空引用数组中的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!