今天在使用ArrayList時,初始化了一個test變量:
ArrayList<Integer> test = new ArrayList<Integer>(3);
test.add(1);
test.add(2);
test.add(3);
當我想刪除其中的3時:
test.remove(3);
卻拋出了異常:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.remove(Unknown Source)
at Game.main(Game.java:32)
我發(fā)現(xiàn)是其中的remove方法出現(xiàn)了問題,于是就去看了下remove方法的具體說明:
remove(int index) : Integer - ArrayList
remove(Object o) : boolean - ArrayList
一般情況在remove括號中輸入整數(shù)它會識別為一個索引,即我們輸入3,那么它會識別為我們要刪除下標為3的元素,但是test中并不存在這個下標元素,所以就拋出了異常,所以當你要刪除3這個元素時,remove應(yīng)該這么寫:
test.remove((Integer)3);
或者通過indexOf方法獲得元素3的索引值進行刪除:
test.remove(test.indexOf(3));