Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java, how to remove an Integer item in an ArrayList

Tags:

java

Suppose I have such an ArrayList:

ArrayList<Integer> list = new ArrayList<Integer>(); 

After the adding operation:

list.add(2); list.add(3); list.add(5); list.add(7); 

I want to remove number 2, if I do

list.remove(2); 

then number 5 will be deleted, how could I delete number 2? And suppose I don't know the index of number 2.

like image 454
betteroutthanin Avatar asked Feb 15 '14 08:02

betteroutthanin


People also ask

How do I remove an integer from a list?

We can remove integers or digits from the list by using python function isinstance(). By using this method, we can get items or elements which does not satisfies the function condition. Here we apply if not condition to check whether the condition is satisfied or not.

How do you remove an item from an ArrayList object?

There are two ways to remove objects from ArrayList in Java, first, by using the remove() method, and second by using Iterator. ArrayList provides overloaded remove() method, one accepts the index of the object to be removed i.e. remove(int index), and the other accept objects to be removed, i.e. remove(Object obj).

Can you delete an element from a list Java?

You cannot remove an element from a list while you're iterating over said list. Make a copy and remove items from that instead, or do it directly to the iterator. With Java 8, the most effective way to do this is use the removeIf(predicate) method on the list.


1 Answers

try this

list.removeAll(Arrays.asList(2)); 

it will remove all elements with value = 2

you can also use this

list.remove(Integer.valueOf(2)); 

but it will remove only first occurence of 2

list.remove(2) does not work because it matches List.remove(int i) which removes element with the specified index

like image 133
Evgeniy Dorofeev Avatar answered Sep 28 '22 10:09

Evgeniy Dorofeev