Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
442 views
in Technique[技术] by (71.8m points)

Arraylist java.lang.IndexOutOfBoundsException: Index 3 out of bounds for length 3 Error

I created a method which takes an Arraylist of string and an integer. It's going to remove all string whose length is less than the given integer.

For example:

Arraylist = ["abcde", "aabb", "aaabbb", "abc", "ab"]

integer = 4

So the new Arraylist should be: ["abcde", "aabb", "aaabbb"]

But I'm getting this error message:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 3 out of bounds for length 3

Here is my code:

public static void main(String[] args){
        ArrayList<String> newArrayList = new ArrayList<>();
        newArrayList.add("string1");
        newArrayList.add("string2");
        newArrayList.add("rem");
        newArrayList.add("dontremove");
        removeElement(newArrayList, 4); // new arraylist must be = [string1, string2, dontremove]
    }


    public static void removeElement(ArrayList<String> arraylist, int inputLen){
        int arrayLen = arraylist.size();
        for(int i=0; i<arrayLen; i++){
            if(arraylist.get(i).length() < inputLen){
                arraylist.remove(i);
                i--;
            }
        }
        System.out.println("New Arraylist: " + arraylist);
    }

What's wrong with this code?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You're looping from 0 to the size of the array which is 4. Inside the loop you're removing items so the size of the array becomes less than 4, so you get this exception. Try looping like this:

Iterator<String> iterator = arraylist.iterator();

while (iterator.hasNext()) {
    String word = iterator.next();
    if (word.length() < inputLen) {
        iterator.remove();
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...