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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…