caiguangbi-53

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);
}

  

 

分类:

技术点:

相关文章:

  • 2021-05-02
  • 2021-11-04
  • 2021-10-18
  • 2021-04-09
  • 2021-04-24
  • 2021-09-14
猜你喜欢
  • 2021-11-14
  • 2021-11-14
  • 2021-11-04
  • 2021-11-11
  • 2021-08-03
  • 2021-11-04
  • 2021-06-27
相关资源
相似解决方案