Iterator Notes.docx - Iterator Notes There are data types...

This preview shows page 1 - 3 out of 7 pages.

Iterator Notes There are data types in programming that does not use indices to indicate where values are. Among those types are Sets, Queues, Stacks, and Linked Lists. In order to traverse these types, an iterator is created. An iterator is an interface that allows the programmer to go from item to item without using indices. Even some data types that do have indices, also include an iterator. An ArrayList is an example of this. Understanding iterators is essential for programming using these data types. There are two types of iterators we will be using. There is the Iterator and the ListIterator, both of which is listed in the API. To use these iterators, you must import them into your code import java.util.Iterator; import java.util.ListIterator; Create a file called Example08 and write the following: import java.util.Iterator; import java.util.*; import static java.lang.System.*; public class ExampleIterators { public static void main(String args []) { ArrayList<Integer> list = new ArrayList<>(); Scanner input = new Scanner( "42 21 17 10 22 12 9 33 4 32 28 31" ); while ( input .hasNext()) list .add( input .nextInt()); Iterator<Integer> iter = list .iterator(); out .println( iter .next()); int value = iter .next(); out .println( value ); while ( iter .hasNext()) iter .next(); out .println( iter .next()); } } The output should look like this: 42 21 Exception in thread "main" java.util.NoSuchElementException at java.util.ArrayList$Itr.next(Unknown Source) at ExampleIterators.main( ExampleIterators.java:24 ) Notice that there is no instantiation for the Iterator. That is because Iterator is an interface and is not instantiated. Instead, it is created by the Object that the iterator will be moving through. Iterator<Integer> iter = list .iterator();
Iterator also needs to have a generic value given to it or it will always hold an Object. Now that there is an iterator created, we need to be able to move through the iterator, and that is done with next() .

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture