本文介绍了为什么会抛出 IndexOutOfBoundsException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

        }
    }

堆栈跟踪:

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)

推荐答案

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.

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

这篇关于为什么会抛出 IndexOutOfBoundsException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-16 14:49