java之ArrayIndexOutOfBoundsException數組越界與IndexOutOfBoundsException索引越界之間關系


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

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM