Java 实现这样一个迭代器?
我有一个Java 实现这样一个迭代器?,java,collections,arraylist,iterator,Java,Collections,Arraylist,Iterator,我有一个HColumn类型的列表(实际上是ArrayList)。现在我想实现一个迭代此集合的迭代器(),这样在迭代时,它会从每个HColumn中给出相应的ColValue 此对象HColumn在java应用程序使用的外部库中定义 如果可能的话,我该怎么做 目前,为了创建这样一个iterable,我一直在创建一个新列表,其中包含相应的ColValues,我想这在性能和效率方面不是一件好事。正如@jordeu所建议的: public class IteratorColValueDecorator i
HColumn
类型的列表(实际上是ArrayList
)。现在我想实现一个迭代此集合的迭代器()
,这样在迭代时,它会从每个HColumn
中给出相应的ColValue
此对象HColumn
在java应用程序使用的外部库中定义
如果可能的话,我该怎么做
目前,为了创建这样一个iterable,我一直在创建一个新列表,其中包含相应的
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
}
公共类迭代器ColValueDecorator实现迭代器{
私有迭代器原件;
//使用原始迭代器的构造函数
公共ColValue next(){
返回original.next().getValue();
}
//其他人只是授权
}
或者,我最初的建议是:
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
}
public类ColValueIterator实现迭代器{
私有列表备份列表;
//建造师录取表
int currentIndex=0;
公共ColValue next(){
返回backingList.get(currentIndex++).getColumn();
}
//通过比较currentIndex和backingList.size()实现hasNext();
//remove()可能引发UnsupportedOperationException(),
//也可以删除当前元素
}
正如@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
}
公共类迭代器ColValueDecorator实现迭代器{
私有迭代器原件;
//使用原始迭代器的构造函数
公共ColValue next(){
返回original.next().getValue();
}
//其他人只是授权
}
或者,我最初的建议是:
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
}
public类ColValueIterator实现迭代器{
私有列表备份列表;
//建造师录取表
int currentIndex=0;
公共ColValue next(){
返回backingList.get(currentIndex++).getColumn();
}
//通过比较currentIndex和backingList.size()实现hasNext();
//remove()可能引发UnsupportedOperationException(),
//也可以删除当前元素
}
我只需要做一个迭代器包装器,就可以在构造函数上得到一个迭代器。是的,这是一个更好的选择。我正在添加它。在机场等了6个小时显然打乱了我的OOP思维:)我只需要做一个迭代器包装器,这样我就可以在构造函数上得到一个迭代器。是的,这是一个更好的选择。我正在添加它。在机场等了6个小时显然打乱了我的OOP思维:)