In this example, we will use ListIterator to remove an element while traversing through elements of ArrayList in Java.
Source Code
package com.beginner.examples;
import java.util.ArrayList;
import java.util.ListIterator;
public class RemoveAnElementUsingListIterator {
public static void main(String[] args) {
//create ArrayList.
ArrayList arrayList = new ArrayList();
arrayList.add("A");
arrayList.add("B");
arrayList.add("C");
arrayList.add("D");
System.out.println("Before removing B, ArrayList contains");
for(int intIndex = 0; intIndex < arrayList.size(); intIndex++) {
System.out.println(arrayList.get(intIndex));
}
//Get an object of ListIterator using listIterator() method.
ListIterator listIterator = arrayList.listIterator();
//remove the element of "B".
listIterator.next();
listIterator.next();
listIterator.remove();
System.out.println("After removing B, ArrayList contains");
for(int intIndex = 0; intIndex < arrayList.size(); intIndex++) {
System.out.println(arrayList.get(intIndex));
}
}
}
Output:
Before removing B, ArrayList contains
A
B
C
D
After removing B, ArrayList contains
A
C
D
References
Imported packages in Java documentation: