Search code examples
javaarraylistindexoutofboundsexception

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?


Solution

  • The length of the array should change when you remove elements. The arrayLen variable stores the length of the array, but doesn't change when the array's length shrinks. To change it, you should be able to just replace arrayLen with arrayList.size(), which will change when your remove elements