Skip to Content

Replace an element from ArrayList using Java ListIterator Example

  1. /*
  2.   Replace an element from ArrayList using Java ListIterator Example
  3.   This Java Example shows how to replace 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 ReplaceAnElementUsingListIteratorExample {
  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 set(Object o) method of ListIterator to replace an element from List.
  29.       It replaces the last element returned by next or previous methods.
  30.       Please note that, set method replaces the element from underlying list.
  31.     */
  32.    
  33.     listIterator.next();
  34.        
  35.     //replace element returned by last next method i.e. 1
  36.     listIterator.set("100");
  37.     /*
  38.       Set method can throw UnsupportedOperationException if set operation
  39.       is not supported by this ListIterator.
  40.      
  41.       In addition to that, it can also throw IllegalStateException if set is
  42.       called before call of neither previous nor next methods or after the last
  43.       call of next or previous methods.
  44.      
  45.       Please also note that, set method can only be called if neither add
  46.       or remove called after last call of next of previous methods.
  47.     */
  48.    
  49.    
  50.     System.out.println("After replacing 1 with 100, ArrayList contains");
  51.     for(int intIndex = 0; intIndex < aList.size(); intIndex++)
  52.       System.out.println(aList.get(intIndex));
  53.    
  54.  
  55.   }
  56. }
  57.  
  58. /*
  59. Output would be
  60. After replacing 1 with 100, ArrayList contains
  61. 100
  62. 2
  63. 3
  64. 4
  65. 5
  66. */