简体   繁体   中英

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?

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!!

java.util.List#remove(int)应该可以工作,只是不要忘记列表的索引为零,即删除了第5个元素,调用list.remove(4)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM