读书人

非常好的一个会合工具类

发布时间: 2014-01-22 00:03:39 作者: rapoo

非常好的一个集合工具类
今天读Heritrix看到这么个类,设计非常棒,多个集合的合并其实并不需要新建集合对象,并进行数据搬移。

public class CompositeIterator<E> implements Iterator<E> {
protected ArrayList<Iterator<E>> iterators = new ArrayList<Iterator<E>>();
protected Iterator<E> currentIterator;
protected int indexOfCurrentIterator = -1;

/**
* Moves to the next (non empty) iterator. Returns false if there are no
* more (non empty) iterators, true otherwise.
* @return false if there are no more (non empty) iterators, true otherwise.
*/
private boolean nextIterator() {
if (++indexOfCurrentIterator < iterators.size()) {
currentIterator = iterators.get(indexOfCurrentIterator);
// If the new iterator was empty this will move us to the next one.
return hasNext();
} else {
currentIterator = null;
return false;
}
}

/* (non-Javadoc)
* @see java.util.Iterator#hasNext()
*/
public boolean hasNext() {
if(currentIterator!=null && currentIterator.hasNext()) {
// Got more
return true;
} else {
// Have got more if we can queue up a new iterator.
return nextIterator();
}
}

/* (non-Javadoc)
* @see java.util.Iterator#next()
*/
public E next() {
if(hasNext()) {
return currentIterator.next();
} else {
throw new NoSuchElementException();
}
}

/* (non-Javadoc)
* @see java.util.Iterator#remove()
*/
public void remove() {
throw new UnsupportedOperationException();
}

/**
* Create an empty CompositeIterator. Internal
* iterators may be added later.
*/
public CompositeIterator() {
super();
}

/**
* Convenience method for concatenating together
* two iterators.
* @param i1
* @param i2
*/
public CompositeIterator(Iterator<E> i1, Iterator<E> i2) {
this();
add(i1);
add(i2);
}

/**
* Add an iterator to the internal chain.
*
* @param i an iterator to add.
*/
public void add(Iterator<E> i) {
iterators.add(i);
}

}

读书人网 >行业软件

热点推荐