Java检查array []项是否存在 [英] Java check if array[] item exists

查看:89
本文介绍了Java检查array []项是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将一些数据下载到String数组中.假设 ImageLinks .如何检查数组中的项是否存在?

I am downloading some data into a String array. Let's say ImageLinks. How do I check if a item in array exist?

我正在尝试

if(ImageLinks[5] != null){}

但是它给了我 ArrayIndexOutOfBoundsException .(因为数组中实际上没有5个链接)

but it gives me ArrayIndexOutOfBoundsException. (Because there are really no 5 link in the array)

推荐答案

要防止 ArrayIndexOutOfBoundsException ,可以使用以下代码:

To prevent the ArrayIndexOutOfBoundsException, you can use the following:

if(ImageLinks.length > 5 && ImageLinks[5] != null)
{
    // do something
}

由于从左到右检查了 if 中的语句,因此如果数组的大小不正确,您将不会进行null检查.

As the statements in the if are checked from left to right, you won't reach the null check if the array doesn't have the correct size.

在任何情况下都可以很容易地将其归纳.

It's quite easy to generalise for any scenario.

这篇关于Java检查array []项是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆