Add element ListIterator java
Below we will create java class to add element using ListIterator because this interface provides operation to add element. We will add element on 1 position in the List and will print output on console:
package com.javahonk.iteratorenumeration; import java.util.ArrayList; import java.util.List; import java.util.ListIterator; public class AddElementListIterator { public static void main(String[] args) { List<String> arrayList = new ArrayList<String>(); arrayList.add("Java"); arrayList.add("Honk"); // get index at 1 and add element ListIterator<String> listIterator = arrayList.listIterator(1); listIterator.add("element added"); listIterator = arrayList.listIterator(); while (listIterator.hasNext()) { String string = (String) listIterator.next(); System.out.println(string); } } }
Output:
Add element ListIterator java done.