DZone

Wednesday, January 19, 2011

A Better Iterator

I've implemented an Iterator, which is a little better than the standard, in a way that it keeps reference to the last returned element.

So it can be used as a regular iterator since it implements java.util.Iterator<E>, but it adds a new method "public E current()", which returns the last element returned by the next() method.

The way it works is by wrapping any given iterator. It can be useful, for instance, when you work with the GoogleCollections API (now called Guava), since internally it is implemented with lazy iterators.

You can pass just this iterator as a parameter to other methods which may collaborate in the process while iterating the elements in a collection. Any method knows and can work with the current element, and also can move the iterator forward, in this case when it returns, the calling method will know the new current element.

Maybe you need it sometime, maybe not. I just want to share it.

Here is the class:


package org.lalala;

import java.util.Collection;
import java.util.Iterator;

public class ImprovedIterator<E> implements Iterator<E> {

 private Iterator<E> delegate;
 private E current;
 private boolean nextCalled;

 public ImprovedIterator(Iterator<E> iterator) {
  this.delegate = iterator;
  this.current = null;
  this.nextCalled = false;
 }

 @Override
 public boolean hasNext() {
  return this.delegate.hasNext();
 }

 @Override
 public E next() {
  this.current = this.delegate.next();
  this.nextCalled = true;
  return this.current;
 }

 @Override
 public void remove() {
  this.current = null;
  this.nextCalled = false;
  this.delegate.remove();
 }

 public E current() {
  if (!this.nextCalled) {
   throw new IllegalStateException("next() was never called or not called again after a remove().");
  }
  return this.current;
 }

 public static <E> ImprovedIterator<E> iteratorFor(Collection<E> collection) {
  return new ImprovedIterator<E>(collection.iterator());
 }

 public static <E> ImprovedIterator<E> iteratorFor(Iterator<E> iterator) {
  return new ImprovedIterator<E>(iterator);
 }

}

Gaston.

No comments:

Post a Comment