Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Item from ArrayList

Tags:

java

arraylist

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.

like image 695
Krishnakant Dalal Avatar asked May 23 '12 05:05

Krishnakant Dalal


People also ask

How do I remove an item from an ArrayList?

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).

How do you remove one object from a list in Java?

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.

How does remove () work in Java?

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.

How do you remove an element from an ArrayList while iterating?

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.


1 Answers

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]); } 
like image 93
Alex Lockwood Avatar answered Sep 28 '22 01:09

Alex Lockwood