String数组如何克服ArrayIndexOutOfBoundsException

时间:2015-06-22 08:25:04

标签: android arraylist

如果您不确定尝试从非现有值读取值位置的数组的长度导致

 Caused by: java.lang.ArrayIndexOutOfBoundsException: length=x; index=x

例如,在excel导入函数中,您期望10列,但文件有9列,然后读取第10列结果到此异常。

处理这种异常的最佳方法是什么?

1 个答案:

答案 0 :(得分:3)

首先 - 数组的索引从0开始,而不是从1开始,如果得到10列,最后一列将使用索引9.如果使用简单数组,则可以检查它的大小像这样:

String[] members = ["He", "She", "It", "The dog"];
int arraySize = members.length;

如果使用ArrayList,可以像这样检查数组的大小:

ArrayList<String> myList = new ArrayList<>();
int arraySize = myList.size();

然后你可以通过这样的值进行for循环:

for(int i = 0; i< arraySize; i++){ ... }

或检查当前索引是否在数组中,如下所示:

//index is a variable with the current index of the element you want
if(index < arraySize){ ... } //do something
else ...

我希望这可以帮助您避免ArrayIndexOutOfBoundsException:)