Answer the question
In order to leave comments, you need to log in
How to remove elements from ArrayList java?
There are two lists, one contains the numbers 1 to 9 and the other contains the numbers to be removed.
List <Integer> list = new ArrayList <Integer> (Arrays.asList(1, 2, 3, 4, 5, 6, 7,8,9));
List <Integer> needRemove = new ArrayList <Integer> (Arrays.asList(3, 4, 5, 9));
for (int i : needRemove) {
if (list.contains(i))
list.remove(i);
}
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 9, Size: 7
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.remove(Unknown Source)
at ExcelID.ExcelArtifact.App.main(App.java:126)
Answer the question
In order to leave comments, you need to log in
Copy the necessary (which do not need to be deleted) elements into the new list. Then replace the first list with the second.
list.remove(i) removes an element at its index (i). The error is correctly given to you, because after each deletion, the size of the list array is reduced and there is no longer an element at index 9 in it.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question