非常好的一个集合工具类

今天读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);
}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值