为什么抛出IndexOutOfBoundsException?

时间:2016-02-19 22:56:02

标签: java exception arraylist indexoutofboundsexception

为什么在以下代码段中抛出IndexOutOfBoundsException? 我似乎无法理解为什么会抛出它?

    import java.util.*;
    public class PrimeNumbers {

        //Printing all prime numbers less than 600 using 'Sieve Method'
        final static int SIZE = 600;
        static ArrayList<Integer> numbers = new ArrayList<Integer>(SIZE);


        public static void populateList(ArrayList<Integer> arraylist){
            for(int i=0; i<SIZE; i++){
                arraylist.add(i, i);
            }
        }

        public static void filterMultiples(ArrayList<Integer> arraylist){
            for(int i=0; i<SIZE; i++){
                if(arraylist.get(i)%2==0 || arraylist.get(i)%3==0 || arraylist.get(i)%5==0){
                    arraylist.remove(i);
                    }
                }
            }

        public static void main(String[] args){
            populateList(numbers);
            filterMultiples(numbers);
            System.out.println(numbers);

        }
    }

STACK TRACE:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 300, Size: 300
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.get(ArrayList.java:429)
at PrimeNumbers.filterMultiples(PrimeNumbers.java:17)
at PrimeNumbers.main(PrimeNumbers.java:25)

2 个答案:

答案 0 :(得分:2)

for(int i=0; i<SIZE; i++){
    if(arraylist.get(i)%2==0 || arraylist.get(i)%3==0 || arraylist.get(i)%5==0){
        arraylist.remove(i);
        }
    }
}

您正在从0迭代到SIZE,但删除元素会导致列表中的元素少于SIZE

答案 1 :(得分:1)

错误在此块中:

imageView

在迭代数组列表时,从中删除元素。因此,它变得更短并且尺寸变得小于实际尺寸(600)。

尝试使用迭代器。它们在迭代时支持修改:

       for(int i=0; i<SIZE; i++){
            if(arraylist.get(i)%2==0 || arraylist.get(i)%3==0 || arraylist.get(i)%5==0){
                arraylist.remove(i);
                }
            }
        }