Why no method like Iterator add to add elements to collection
Answer : Please see below:
Iterator:
–> J A V A
–> 0 1 2 3
^ ^ ^ ^
Iterator traverse only in forward direction due it cursor points middle position and calling next will move cursor to the next position. But sole purpose is by design Iterator created only to iterate through element and remove element during iteration.
ListIterator:
–> J A V A
–> 0 1 2 3
^ ^ ^ ^ ^
ListIterator could traverse in either direction. As could see above ListIterator having no current element and its cursor (denoted by carets ^) position lies between the element and that would be returned by calling previous() or next(). For example if ListIterator has length n then cursor position would be n+1.
Now add value during iteration is possible and once value added to that position then cursor will be pointing to middle again.
Please see example of add element using ListIterator:
package com.javahonk.iteratorenumeration; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.ListIterator; public class ListIteratorTest { public static void main(String[] args) { List<String> arrayList = new ArrayList<String>(); arrayList.add("Java"); arrayList.add("Honk"); Iterator<String> iterator = arrayList.iterator(); System.out.println("Origional list:"); while (iterator.hasNext()) { String string = (String) iterator.next(); System.out.println(string); } // get index at 1 and add element System.out.println("\nAfter element added to list:"); 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); } // Modify objects being iterated. ListIterator<String> litr = arrayList.listIterator(); while (litr.hasNext()) { String element = litr.next(); litr.set(element + "+"); } System.out.print("\nModified contents of List: "); iterator = arrayList.iterator(); while (iterator.hasNext()) { String element = iterator.next(); System.out.print(element + " "); } System.out.println(); // Now, display the list backwards. System.out.print("\nModified list backwards: "); while (litr.hasPrevious()) { String element = litr.previous(); System.out.print(element + " "); } System.out.println(); } }
Output: