WorkHardDieSoon
WorkHardDieSoon

Reputation: 11

Remove a specific element from an Arraylist in Java?

I have an Arraylist with (String-)Arrays in it. Now I want to be able to delete a specific element from the Arraylist.

Here is an example arraylist:

0:  [Name, , , ]
1:  [Telefon, \(\d+\) \d+, DAFAE8, FF6262]
2:  [E-Mail, ^[a-zA-Z0-9]+(?:(\.|_)[A-Za-z0-9!#$%&'*+/=?^`{|}~-]+)*@(?!([a-zA-Z0-9]*\.[a-zA-Z0-9]*\.[a-zA-Z0-9]*\.))(?:[A-Za-z0-9](?:[a-zA-Z0-9-]*[A-Za-z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$, DAFAE8, FF6262]
3:  [Company, , , ]
4:  [Test, , , ]
5:  [Test2, , , ]
6:  [Test3, , , ]

Now I want to delete the 5th element (the array which includes Test2). How do I accomplish that?

I already tried the following things:

public static List<String[]> removeSpecificElements(List<String[]> list, int i){
    list.remove(new Integer(i));
    return list;
}

This one doesn't throw any kind of Exception, but doesn't work either.

public static List<String[]> removeSpecificElements(List<String[]> list, int i){
    list.remove(i);
    return list;
}

This one throws ArrayIndexOutOfBounds.

public static List<String[]> removeSpecificElements(List<String[]> list, int i){
    Iterator<String[]> itr = list.iterator();
    itr.next();
    for (int x = 0; x < i; x++){
        itr.next();
        System.out.println(itr);
    }
    itr.remove();
    return list;
}

And this one always removes the first element.

Could you please help me?

Upvotes: 0

Views: 1600

Answers (2)

Peter Lawrey
Peter Lawrey

Reputation: 533880

Now I want to delete the 5th element (the array which includes Test2). How do I accomplish that?

You need to use

list.remove(i); // where i = 5 - 1, as the first element is 0.

if you do

list.remove(new Integer(i));

it will look for the object you just created, which doesn't exist in the list, so as you say it does nothing.

In short, don't confuse int for Integer as these are different types.

Ideally, the API would have a different method like removeAt(int) to remove this potential source of confusion, but it's too late to change it now.


When would this work? Consider the following.

List<Integer> ints = new ArrayList<>();
ints.add(4);

List<MyType> list = (List) ints; // it works but don't do this.
boolean wasRemoved = list.remove(new Integer(4)); // true!!

Upvotes: 4

Boris Pavlović
Boris Pavlović

Reputation: 64650

java.util.List#remove(int) should work, just don't forget that lists are zero indexed, i.e. 5th element is removed calling list.remove(4)

Upvotes: 3

Related Questions