Why is IndexOutOfBoundsException Thrown?

[亡魂溺海] 提交于 2019-12-13 08:29:33

问题


Why is the IndexOutOfBoundsException thrown in the following code segment? I can’t seem to understand why it is thrown?

    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)

回答1:


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

You're iterating from 0 to SIZE, but removing elements will cause there to be fewer than SIZE elements in the list.




回答2:


The error is in this block:

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

While you iterate through the array list, you remove element from it. Thus, it gets shorter and the size becomes smaller than the actual size (600).

Try using iterators instead. They support modification while iterating:

    for (Iterator<Integer> iterator = numbers.iterator(); iterator.hasNext();) {
        int number = iterator.next();
        if (number % 2 == 0 || number % 3 == 0
                || number % 5 == 0) {
            iterator.remove();
        }
    }


来源:https://stackoverflow.com/questions/35516592/why-is-indexoutofboundsexception-thrown

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!