Arraylist java.lang.IndexOutOfBoundsException:索引3超出长度3的范围错误 [英] Arraylist java.lang.IndexOutOfBoundsException: Index 3 out of bounds for length 3 Error

查看:166
本文介绍了Arraylist java.lang.IndexOutOfBoundsException:索引3超出长度3的范围错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

例如:

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

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

整数= 4

因此,新的 Arraylist 应该为:[" abcde," aabb," aaabbb]

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

但是我收到此错误消息:

But I'm getting this error message:

线程"main"中的异常;java.lang.IndexOutOfBoundsException:索引3的长度为3

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

此代码有什么问题?

推荐答案

删除元素时,数组的长度应更改. arrayLen 变量存储数组的长度,但是当数组的长度缩小时不会改变.要对其进行更改,您应该只需将 arrayLen 替换为 arrayList.size(),当您删除元素时,该值就会更改

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

这篇关于Arraylist java.lang.IndexOutOfBoundsException:索引3超出长度3的范围错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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