T
T
thatmaniscool2019-12-16 11:04:32
Java
thatmaniscool, 2019-12-16 11:04:32

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

Gives an error that the program has gone beyond the array.
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)

Tried through the iterator, but the elements are not removed.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
022y, 2019-12-16
@022y

Copy the necessary (which do not need to be deleted) elements into the new list. Then replace the first list with the second.

O
Oksana ..., 2019-12-16
@deniz1983

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 question

Ask a Question

731 491 924 answers to any question