ArrayIndexOutOfBoundsException与IndexOutOfBoundsException之间的关系是继承关系,看源代码就可以知道:
public class ArrayIndexOutOfBoundsException extends IndexOutOfBoundsException {}
那么什么情况会出现ArrayIndexOutOfBoundsException呢?这种异常针对的是数组Array的使用过程中出现的错误
public static void main(String[] args) { int[] arr = {1, 2, 3}; for (int i = 0; i <= arr.length; i++) { System.out.println(arr[i]); // 因为a[4]获取第四个值时报的错 } }
那么什么情况会出现IndexOutOfBoundsException呢?这种异常针对的是list集合在使用过程中出现的错误
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("aa");
list.add("bb");
list.add("cc");
list.add("dd");
list.add("ee");
/**
* 只求取list.size()长度一次
* i == 0 len == 5 list.remove(0) list剩下["bb","cc","dd","ee"]
* i == 1 len == 5 list.remove(1) list剩下["bb", "dd","ee"]
* i == 2 len == 5 list.remove(2) list剩下["bb","dd"]
* i == 3 len == 5 list.remove(3) list因为没有第四个元素,于是报索引越界错误
*/
int len = list.size();
for (int i = 0; i < len; i++) {
list.remove(i);
}
System.out.println(list);
}