文档

java_lang_ArrayIndexOutOfBoundsException

问题分析

数组索引越界,引用的对象超出了数组的大小。

解决方案

数组索引越界,引用的对象超出了数组的大小。因此在操作数组之前查看数组大小,判断对象是否存在,如果存在则返回,否则返回null。

示例代码

public String arrayOutOfBounds(String[] array, int index){
    if(array!=null && array.length>index && index>=0){
        System.out.println("content is: "+array[index]);
        return array[index];
    }
    return null;
}

详细例子:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at com.alibaba.mqc.test.Test.arrayOutOfBounds(Test.java:52)
at com.alibaba.mqc.test.Test.main(Test.java:31)

这种Crash是数组本身大小为0而代码中获取了数组的对象而导致的。在SourceFile文件第86行对数组进行get操作时index越界导致的。

参考文献

  • 本页导读 (0)
文档反馈