简体   繁体   English

Java ArrayList避免IndexOutOfBoundsException

[英]Java ArrayList avoiding IndexOutOfBoundsException

i got a short question. 我有一个简短的问题。

ArrayList<T> x = (1,2,3,5)

int index = 6
if (x.get(6) == null) {
    return 0;
}

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 6, Size: 4

How can I avoid this? 我怎么能避免这个? I just want to check if there is something in the array with index 6. If there is (null)/(nothing there) i want to return 0. 我只想检查数组中是否有索引6的内容。如果有(null)/(没有)我想返回0。

Just use the size of the list (it's not an array): 只需使用列表的大小(它不是数组):

if (x.size() <= index || x.get(index) == null) {
    ...
}

Or if you want to detect a valid index with a non-null value, you'd use: 或者,如果要检测具有非空值的有效索引,则使用:

if (index < x.size() && x.get(index) != null) {
    ...
}

In both cases, the get call will not be made if the first part of the expression detects that the index is invalid for the list. 在这两种情况下,如果表达式的第一部分检测到索引对列表无效,则不会进行get调用。

Note that there's a logical difference between "there is no element 6" (because the list doesn't have 7 elements) and "there is an element 6, but its value is null" - it may not be important to you in this case, but you need to understand that it is different. 请注意,“没有元素6”(因为列表没有7个元素)和“有一个元素6,但它的值为空”之间存在逻辑差异 - 在这种情况下,它可能对您不重要,但你需要明白它不同的。

check size of arraylist. 检查arraylist的大小。 if size is less that 6 then return 0 else return value 如果size小于6,则返回0 else返回值

Check the size of the list first by using size() , then check for the index. 首先使用size()检查列表的size() ,然后检查索引。

if (x.size() <= 6 || x.get(6) == null) {
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM