Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

improved collection Iterator

Personally, I find the range of functionality provided by java.util.Iterator to be fairly pathetic. At a minimum, I'd like to have methods such as:

  • peek() returns next element without moving the iterator forward
  • previous() returns the previous element

Though there are lots of other possibilities such as first() and last().

Does anyone know if such a 3rd party iterator exists? It would probably need to be implemented as a decorator of java.util.Iterator so that it can work with the existing java collections. Ideally, it should be "generics aware".

Thanks in advance, Don

like image 420
Dónal Avatar asked Oct 10 '08 17:10

Dónal


People also ask

What is collection Iterator?

An Iterator is an object that can be used to loop through collections, like ArrayList and HashSet. It is called an "iterator" because "iterating" is the technical term for looping. To use an Iterator, you must import it from the java.util package.

How do you traverse through a collection using its Iterator?

To use an iterator to cycle through the contents of a collection, at first obtain an iterator to the start of the collection by calling the collection's iterator( ) method. After that, set up a loop that makes a call to hasNext( ). Have the loop iterate as long as hasNext( ) returns true.

Why Iterator is used instead of for loop?

In for-each loop, we can't modify collection, it will throw a ConcurrentModificationException on the other hand with iterator we can modify collection. Modifying a collection simply means removing an element or changing content of an item stored in the collection.


1 Answers

You can get previous() easily by just using a java.util.ListIterator.

Peek at that point is easily implemented by doing a

public <T> T peek(ListIterator<T> iter) throws NoSuchElementException {
    T obj = iter.next();
    iter.previous();
    return obj;
}

Unfortunately it will be easier to have it as a utility method since each collection class implements their own iterators. To do a wrapper to get a peek method on each collection on some interface such as MyListIterator would be quite a lot of work.

like image 120
William Avatar answered Oct 09 '22 02:10

William