Arraylist java.lang.IndexOutOfBoundsException: 索引 3 超出长度 3 错误的范围

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

我创建了一个方法,它接受一个 Arraylist 字符串和一个整数。它将删除所有长度小于给定整数的字符串。

例如:

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

整数 = 4

所以新的 Arraylist 应该是:["abcde", "aabb", "aaabbb"]

但我收到此错误消息:

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

这是我的代码:

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

这段代码有什么问题?

int arrayLen = arraylist.size();

问题是您的索引值为 4。

但是一旦您从列表中删除一个项目,您现在只有 3 个条目。

因此在您的循环中,当您尝试访问第 4 个条目时,您现在将收到 IndexOutOfBounds 错误。

解决方法是从ArrayList的末尾开始,倒数到0。

For (int i = arrayLen - 1; i >= 0; i--)

在循环中你不需要:

i--;

您正在修改列表,同时遍历其索引。删除第一项后,列表将比您预期的要短,并且一旦到达原始最后一个元素的索引,您就会收到此错误。幸运的是,removeIf 方法可以为您完成繁重的工作:

public static void removeElement(List<String> arraylist, int inputLen) {
    arraylist.removeIf(s -> s.length() < inputLen);
    System.out.println("New Arraylist: " + arraylist);
}

当您删除元素时,数组的长度应该会改变。 arrayLen 变量存储数组的长度,但在数组长度缩小时不会改变。要更改它,您应该能够将 arrayLen 替换为 arrayList.size(),这将在您删除元素时更改

您正在从 0 循环到数组大小为 4。在循环中您正在删除项目,因此数组大小变得小于 4,因此您会遇到此异常。 尝试像这样循环:

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

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