为什么抛出IndexOutOfBoundsException? [英] Why is IndexOutOfBoundsException Thrown?

查看:116
本文介绍了为什么抛出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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆