Remove an element from an ArrayList using the ListIterator in Java


An element can be removed from an ArrayList using the ListIterator method remove(). This method removes the current element in the ArrayList. If the remove() method is not preceded by the next() method, then the exception IllegalStateException is thrown.

A program that demonstrates this is given as follows.

Example

 Live Demo

import java.util.ArrayList;
import java.util.ListIterator;
public class Demo {
   public static void main(String[] args) {
      ArrayList<String> aList = new ArrayList<String>();
      aList.add("Apple");
      aList.add("Mango");
      aList.add("Guava");
      aList.add("Orange");
      aList.add("Peach");
      System.out.println("The ArrayList elements are: ");
      for (String s: aList) {
         System.out.println(s);
      }
      ListIterator li = aList.listIterator();
      li.next();
      li.remove();
      System.out.println("
The element Apple is removed");       System.out.println("
The ArrayList elements are: ");       for (String s: aList) {          System.out.println(s);       }    } }

Output

The output of the above program is as follows −

The ArrayList elements are:
Apple
Mango
Guava
Orange
Peach

The element Apple is removed

The ArrayList elements are:
Mango
Guava
Orange
Peach

Updated on: 29-Jun-2020

702 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements