我正在将一些数据下载到一个字符串数组中,假设叫做ImageLinks
。如何检查数组中是否存在一个元素?
我正在尝试。
if(ImageLinks[5] != null){}
但是它给了我一个ArrayIndexOutOfBoundsException
异常。(因为数组中确实没有第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)
它会抛出一个空异常,不是吗? - sdlins编写一个静态函数
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
情况。 - Baztrue
或false
检查_,是非常糟糕的。 2) is...Exists
是不好的命名方式。 - CosmicGiant在进行查找之前,请确保数组长度正确。
if(ImageLinks.length > 5 && ImageLinks[5] != null){}
它失败的原因是数组元素少于6个。
首先检查数组是否具有正确数量的元素,然后检查该元素是否存在于数组中。
if (ImageLinks.length > 5 && ImageLinks[5] != null) {
// do something
}
是的,少于6个元素。 ImageLinks[5]指的是第六个元素,因为在Java中,数组索引从0开始。
if (ImageLinks != null && Stream.of(ImageLinks).anyMatch(imageLink-> imageLink != null)) {
//An item in array exist
}