From charlesreid1

No edit summary
No edit summary
 
(2 intermediate revisions by the same user not shown)
Line 1: Line 1:
Also see [[Java/Iterable#Iterable vs Iterator]]
Also see [[Java/Iterable#Iterable vs Iterator]]


Iterator is a wrapper class - think of it as a lightweight scanner object for an iterable data container.
Iterator is a wrapper class - think of it as a lightweight scanner object for an iteration-capable data container.


The Linked List class ([https://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html javadocs link]) utilizes a ListIterator class ([http://docs.oracle.com/javase/7/docs/api/java/util/ListIterator.html javadocs link]). The ListIterator class is basically similar to the Iterator class but adds a few additional methods - add, hasPrevious, previous, hasNext, next, etc.
The List interface class ([http://docs.oracle.com/javase/7/docs/api/java/util/List.html javadocs link]) and Linked List class ([https://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html javadocs link]) both utilize a very handy ListIterator class ([http://docs.oracle.com/javase/7/docs/api/java/util/ListIterator.html javadocs link]) to iterate over items in a list. The ListIterator class extends the Iterator class, adding a few additional methods - add, hasPrevious, previous, hasNext, next, etc.


To get a ListIterator to a list, use listIterator() method.
To get a ListIterator to a list, use listIterator() method.


To get a ListIterator to a list pointing to index i, use the listIterator(int i) method.
To get a ListIterator to a list pointing to index i, use the listIterator(int i) method.
Note that Java's Collections linked list is a doubly linked list, so the previous method is O(1), not O(N).
==Flags==
[[Category:Java]]
[[Category:Iteration]]
[[Category:OOP]]
[[Category:CS]]

Latest revision as of 07:03, 19 June 2017

Also see Java/Iterable#Iterable vs Iterator

Iterator is a wrapper class - think of it as a lightweight scanner object for an iteration-capable data container.

The List interface class (javadocs link) and Linked List class (javadocs link) both utilize a very handy ListIterator class (javadocs link) to iterate over items in a list. The ListIterator class extends the Iterator class, adding a few additional methods - add, hasPrevious, previous, hasNext, next, etc.

To get a ListIterator to a list, use listIterator() method.

To get a ListIterator to a list pointing to index i, use the listIterator(int i) method.

Note that Java's Collections linked list is a doubly linked list, so the previous method is O(1), not O(N).



Flags