【发布时间】:2012-10-05 13:04:04
【问题描述】:
我正在将一些数据下载到一个字符串数组中。假设ImageLinks。
如何检查数组中的项目是否存在?
我在努力
if(ImageLinks[5] != null){}
但它给了我ArrayIndexOutOfBoundsException。 (因为数组中真的没有5个链接)
【问题讨论】:
-
if (ImageLinks.length > 5)??
我正在将一些数据下载到一个字符串数组中。假设ImageLinks。
如何检查数组中的项目是否存在?
我在努力
if(ImageLinks[5] != null){}
但它给了我ArrayIndexOutOfBoundsException。 (因为数组中真的没有5个链接)
【问题讨论】:
if (ImageLinks.length > 5) ??
要防止ArrayIndexOutOfBoundsException,您可以使用以下内容:
if(ImageLinks.length > 5 && ImageLinks[5] != null)
{
// do something
}
由于if 中的语句是从左到右检查的,因此如果数组的大小不正确,您将无法进行空检查。
很容易概括任何场景。
【讨论】:
a[0] = 20; a[5] = 30; 一样。如果我检查if(a.length > 4 && a[4] != null),它会抛出一个空异常,不是吗?
写一个静态函数
public static boolean indexInBound(String[] data, int index){
return data != null && index >= 0 && index < data.length;
}
现在,在你的代码中调用它
if(indexInBound(ImageLinks, 5) && ImageLinks[5] != null){
//Your Code
}
【讨论】:
null 的情况。
true 或false 检查中,是非常不好。 2) is...Exists 命名不好。
在进行查找之前确保数组具有该长度
if(ImageLinks.length > 5 && ImageLinks[5] != null){}
【讨论】:
它失败的原因是数组的元素少于 6 个。
先检查数组的元素个数是否正确,再检查该元素是否存在于数组中。
if (ImageLinks.length > 5 && ImageLinks[5] != null) {
// do something
}
【讨论】:
是的,元素少于 6 个 ImageLinks[5] 引用第 6 个元素作为 java 中的数组索引从 0 开始
【讨论】:
if (ImageLinks != null && Stream.of(ImageLinks).anyMatch(imageLink-> imageLink != null)) {
//An item in array exist
}
【讨论】: