我有一个类型为 ArrayList
的列表(实际上是 HColumn<ColName, ColValue>
) 。现在我想实现一个iterator()
迭代此集合,以便在迭代时给出相应的 ColValue
来自每个 HColumn
.
此对象HColumn<ColName, ColValue>
是在我的 java 应用程序使用的外部库中定义的。
如果可能的话,我怎样才能做到这一点?
目前,为了创建这样一个可迭代对象,我一直在创建一个新列表,其中包含相应的 ColValues
我认为就性能和效率而言这不是一件好事。
最佳答案
按照@jordeu的建议:
public class IteratorColValueDecorator implements Iterator<ColValue> {
private Iterator<HColumn<ColName, ColValue>> original;
//constructor taking the original iterator
public ColValue next() {
return original.next().getValue();
}
//others simply delegating
}
或者,我最初的建议:
public class ColValueIterator implements Iterator<ColValue> {
private List<HColumn<ColName, ColValue>> backingList;
//constructor taking List<...>
int currentIndex = 0;
public ColValue next() {
return backingList.get(currentIndex++).getColumn();
}
//hasNext() implemented by comparing the currentIndex to backingList.size();
//remove() may throw UnsupportedOperationException(),
//or you can remove the current element
}
关于java - 实现这样的迭代器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9863846/