tags:

views:

148

answers:

6

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.

+2  A: 

You can use Collection.removeAll(toRemove) if you have a separate list of objects to remove.

http://download.oracle.com/javase/6/docs/api/java/util/Collection.html

If your collection is indexed based, like ArrayList is, you can call

remove(index)

to remove the element at the index. You can do that in a loop, but beware that removing shifts all the indexes as another answer points out.

If all you want to do is remove the first two elements from the list, then

   list.remove(0);
   list.remove(0);

should do it.

hvgotcodes
my mistake I read too fast and thought he was trying to prevent duplicate items. removeAll is still over kill in this scenario
Woot4Moo
But `removeAll` will remove **all occurrences** of the elements contain in the argument, from the callee, that is, it is not the same as removing the first to elements of the ArrayList.
aioobe
@aioobe you are right.
hvgotcodes
+3  A: 

You can certainly do that

    ArrayList ar1 = new ArrayList();
    ar1.add("a");
    ar1.add("b");
    ar1.add("c");
    ar1.add("d");

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

Only pay attention that after you remove first element, other elements shift. Thus, calling

ar1.remove(0);
ar1.remove(1);

will effectively remove first and third elements from the list. This will delete first two elements, though:

ar1.remove(0);
ar1.remove(0);
Nikita Rybak
In what way does this depend on the type of thing being stored in the list?
Stephen P
@Stephen My bad, I confused things.
Nikita Rybak
+3  A: 

For indexed removals from a list, you need to count backwards:

 for (int i = 1; i >= 0; i--)

otherwise, your first removal shifts the items "above" it in the collection and you don't wind up removing the items you think you are removing.

Larry Lustig
+1  A: 

You could try this:

List<Whatever> l = new ArrayList<Whatever>();
l.add(someStuff);
Iterator<Whatever> it = l.iterator();
int i = 0;
while (i < 2 && it.hasNext()) {
    it.next();
    it.remove();
    i++;
}

Or, more generally:

List<Whatever> l = new ArrayList<Whatever>();
l.add(someStuff);
Iterator<Whatever> it = l.iterator();
while (it.hasNext()) {
    Whatever next = it.next();
    if (shouldRemove(next)) {
        it.remove();
    }
}

EDIT: I guess it depends if you are trying to remove particular indices or particular objects. It also depends on how much logic you need to decide if something should be removed. If you know the indices then remove them in reverse order. If you have a set of Objects to be removed, then use removeAll. If you want to iterate over the list and remove objects that match a predicate then use the above code.

Cameron Skinner
Ah, yes. Thanks, Erick. StackOverflow really needs a compiler built into the answer pane so we can test our code :)
Cameron Skinner
+12  A: 

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.

ColinD
+1 excellent answer.
aioobe
+1 It's what the API docs suggest you do. (May commonly not be as efficient as multiple `remove` calls.)
Tom Hawtin - tackline
Unless the items the OP wants to remove aren't sequential. Depends on the details.
Erick Robertson
@Erick: In the example he gives of what he wants to do, it seems that he's trying to remove the first two elements of the list, which are obviously sequential. If there's something else he wants to do, that's a different question and a different answer.
ColinD
The question is to "remove multiple elements". This solution will only work to "remove multiple sequential elements", which is the example given.
Erick Robertson
@Erick: I generally don't base my answers on the title... the question itself is often much more specific.
ColinD
I needed sequential elements, sorry for not specifying...this subList.remove() is what I ended up using thank you very much for your help.
acesnap
+2  A: 

If you know the indexes of the items you want to remove, you can remove them in reverse order, without worrying about shifting indexes:

    ArrayList ar1 = new ArrayList();
    ar1.add("a");
    ar1.add("b");
    ar1.add("c");
    ar1.add("d");

    int[] indexesToRemove = {0,2,3};
    Arrays.sort(indexesToRemove);
    for (int i=indexesToRemove.length-1; i>=0; i--) {
        ar1.remove(indexesToRemove[i]);
    }
Hippo