I have an ArrayList
suppose list
, and it has 8 items A-H and now I want to delete 1,3,5 position Item stored in int array from the list
how can I do this.
I am trying to do this with
ArrayList<String> list = new ArrayList<String>(); list.add("A"); list.add("B"); list.add("C"); list.add("D"); list.add("E"); list.add("F"); list.add("G"); list.add("H"); int i[] = {1,3,5}; for (int j = 0; j < i.length; j++) { list.remove(i[j]); }
But after first item deleted positioned of array is changed and in the next iterate it deletes wrong element or give exception.
Using the remove() method of the ArrayList class is the fastest way of deleting or removing the element from the ArrayList. It also provides the two overloaded methods, i.e., remove(int index) and remove(Object obj).
The remove(Object obj) method of List interface in Java is used to remove the first occurrence of the specified element obj from this List if it is present in the List. Parameters: It accepts a single parameter obj of List type which represents the element to be removed from the given List.
Return values of remove() in JavaThe remove method returns true if an object passed as a parameter is removed from the list. Otherwise, it returns false. The remove method returns the removed element if an index is passed. It throws IndexOutOfBoundsException if the specified index is not in range.
The right way to remove objects from ArrayList while iterating over it is by using the Iterator's remove() method. When you use iterator's remove() method, ConcurrentModfiicationException is not thrown.
In this specific case, you should remove the elements in descending order. First index 5
, then 3
, then 1
. This will remove the elements from the list without undesirable side effects.
for (int j = i.length-1; j >= 0; j--) { list.remove(i[j]); }
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