Skip to Content

Remove an element from ArrayList using Java ListIterator Example

  1. /*
  2.   Remove an element from ArrayList using Java ListIterator Example
  3.   This Java Example shows how to remove an element while traversing through
  4.   elements of ArrayList using Java ListIterator.
  5. */
  6.  
  7. import java.util.ListIterator;
  8. import java.util.ArrayList;
  9.  
  10. public class RemoveAnElementUsingListIteratorExample {
  11.  
  12.   public static void main(String[] args) {
  13.    
  14.     //create an object of ArrayList
  15.     ArrayList aList = new ArrayList();
  16.    
  17.     //Add elements to ArrayList object
  18.     aList.add("1");
  19.     aList.add("2");
  20.     aList.add("3");
  21.     aList.add("4");
  22.     aList.add("5");
  23.    
  24.     //Get an object of ListIterator using listIterator() method
  25.     ListIterator listIterator = aList.listIterator();
  26.  
  27.     /*
  28.       Use void remove() method of ListIterator to remove an element from List.
  29.       It removes the last element returned by next or previous methods.
  30.       Please note that, remove method removes the element from underlying list.
  31.     */
  32.    
  33.     listIterator.next();
  34.     listIterator.next();
  35.    
  36.     //remove element returned by last next method
  37.     listIterator.remove();
  38.     /*
  39.       Remove method can throw UnsupportedOperationException if remove operation
  40.       is not supported by this ListIterator.
  41.      
  42.       In addition to that, it can also throw IllegalStateException if remove is
  43.       called before call of neither previous nor next methods or after the last
  44.       call of next or previous methods.
  45.     */
  46.    
  47.    
  48.     System.out.println("After removing 2, ArrayList contains");
  49.     for(int intIndex = 0; intIndex < aList.size(); intIndex++)
  50.       System.out.println(aList.get(intIndex));
  51.    
  52.  
  53.   }
  54. }
  55.  
  56. /*
  57. Output would be
  58. After removing 2, ArrayList contains
  59. 1
  60. 3
  61. 4
  62. 5
  63. */