How to remove element from arraylist in java

Let’s learn how to remove element from arraylist in java.

How to remove element from arraylist in java

To remove element from arraylist remove() method is used. remove() method removes the element at the specified position in the given list.

how to remove element from arraylist in java

Remove method has two overloaded methods,

  • remove(int index) – removes first specified element from list.
  • remove(Object o) – removes element at specified position in given list.

Let’s see java program on ArrayList remove(int index) method example.

import java.util.ArrayList;
import java.util.List;
public class ArrayListRemoveIndex
{
   public static void main(String[] args)
   {
      List<Integer> al = new ArrayList<>();
      al.add(56);
      al.add(28);
      al.add(39);
      al.add(59);
      al.add(82);
      System.out.println("Before using ArrayList.remove(int index) method: " + al);
      // removes element 28
      al.remove(1);
      // element 39 is now moved one position back
      // So element 39 is removed
      al.remove(1);
      System.out.println("After using ArrayList.remove(int index) method: " + al);
   }
}


Output:

Before using ArrayList.remove(int index) method: [56, 28, 39, 59, 82]
After using ArrayList.remove(int index) method: [56, 59, 82]

As you can see the output, the passed parameter is considered as index. Remove (int index) method accepts index to be removed as parameter.


arraylist remove(Object o) method in java


NOTE:

ArrayList.remove() method is not recommended to use while iterating over elements. Because it will throw ConcurrentModificationException. Instead use Iterator’s remove() method.


Iterator.remove() method

Here we will learn how to remove an element from arraylist using Iterator’s remove() method.

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class IteratorRemoveDemo
{
   public static void main(String[] args)
   {
      List<Integer> al = new ArrayList<>();
      al.add(56);
      al.add(28);
      al.add(39);
      al.add(59);
      al.add(82);
      System.out.println("Before removing element using Iterator remove() method: " + al);
      Iterator<Integer> iterate = al.iterator();
      while(iterate.hasNext())
      {
         int r = (Integer)iterate.next();
         if(r > 50)
         {
            iterate.remove();
         }
      }
      System.out.println("After removing element using Iterator remove() method: " + al);
   }
}


Output:

Before removing element using Iterator remove() method: [56, 28, 39, 59, 82]
After removing element using Iterator remove() method: [28, 39]

Reference – docs oracle

Also read – Strings in java