Skip to Content

Add or insert an element to ArrayList using Java ListIterator Example

  1. /*
  2.   Add or insert an element to ArrayList using Java ListIterator Example
  3.   This Java Example shows how to add or insert 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 AddAnElementUsingListIteratorExample {
  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 add(Object o) method of ListIterator to add or insert an element
  29.       to List. It adds an element just before the element that would have
  30.       been returned by next method call and after the element that would have
  31.       returned by previous call.
  32.     */
  33.    
  34.     listIterator.next();
  35.        
  36.     //Add an element
  37.     listIterator.add("Added Element");
  38.     /*
  39.       add method can throw UnsupportedOperationException if add operation
  40.       is not supported by this ListIterator.
  41.      
  42.       Please also note that, sebsequent call to previous method after adding
  43.       an element, would return the newly added element.
  44.     */
  45.    
  46.    
  47.     System.out.println("After inserting element, ArrayList contains");
  48.     for(int intIndex = 0; intIndex < aList.size(); intIndex++)
  49.       System.out.println(aList.get(intIndex));
  50.    
  51.  
  52.   }
  53. }
  54.  
  55. /*
  56. Output would be
  57. After inserting element, ArrayList contains
  58. 1
  59. Added Element
  60. 2
  61. 3
  62. 4
  63. 5
  64. */

Advertisement: