I am trying to remove all occurrences of an item in the arraylist
ArrayList list=new ArrayList();
list.Add("2.2");
list.Add("2.5");
list.Add("2.6");
list.Add("2.2");
list.Add("2.5");
list.Add("2.2");
How can remove all 2.2 values from the list?I have used
list.Remove("2.2")
but it removes only first occurrence
Core Java bootcamp program with Hands on practice The List provides removeAll() method to remove all elements of a list that are part of the collection provided.
If the elements in the array are no longer desired and what you want is an empty array (i.e., an array with zero elements) ready to be used again then you can use myArray. clear(); or myArray = new ArrayList(); .
Read the docs on ArrayList.Remove(), in particular:
Removes the first occurrence of a specific object from the ArrayList.
Why are you using an ArrayList
anyway? The elements in your example are all the same type, you would be better off using a List<string>
and then using RemoveAll e.g.
List<string> list = new List<string>();
list.add("2.2");
list.add("2.5");
list.add("2.6");
list.add("2.2");
list.add("2.5");
list.add("2.2");
list.RemoveAll(item => item == "2.2");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With