问题描述
限时送ChatGPT账号..我创建了一个方法,它采用字符串和整数的 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"]
但我收到此错误消息:
线程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屋!
更多推荐
[db:关键词]
发布评论