Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove sequential elements from a Java ArrayList?

Tags:

java

arraylist

I'm a relatively new Java programmer and I'm having difficuly removing more than one element from an ArrayList. Ideally I'd like to do something like this:

ArrayList ar1 = new ArrayList();
ar1.add(...)
ar1.add(...)
ar1.add(...)
ar1.add(...)

for (int i = 0; i < 2; i++){
     ar1.remove(i);
}

I think iterator might help, but I can't find an example that matches close enough to what I'm trying to do. Any help would be appreciated. Thanks.

like image 330
acesnap Avatar asked Oct 22 '10 16:10

acesnap


People also ask

How do I remove multiple elements from an ArrayList?

The List provides removeAll() method to remove all elements of a list that are part of the collection provided.

Can we remove element from ArrayList while iterating?

ArrayList provides the remove() methods, like remove (int index) and remove (Object element), you cannot use them to remove items while iterating over ArrayList in Java because they will throw ConcurrentModificationException if called during iteration.


1 Answers

Here's what you want to do:

ar1.subList(0, 2).clear();

This creates a sublist view of the first 2 elements of the list and then clears that sublist, removing them from the original list. The subList method exists primarily for this sort of thing... doing operations on a specific range of the list.

like image 191
ColinD Avatar answered Sep 22 '22 14:09

ColinD