【发布时间】:2015-12-21 08:51:39
【问题描述】:
我想了解迭代器设计模式,并在以下教程中找到。
http://www.journaldev.com/1716/iterator-design-pattern-in-java-example-tutorial
以下是hasNext() 和next() 方法的代码。
@Override
public boolean hasNext() {
while (position < channels.size()) {
Channel c = channels.get(position);
if (c.getTYPE().equals(type) || type.equals(ChannelTypeEnum.ALL)) {
return true;
} else
position++;
}
return false;
}
@Override
public Channel next() {
Channel c = channels.get(position);
position++;
return c;
}
使用上述方法集合迭代的是
while (baseIterator.hasNext()) {
Channel c = baseIterator.next();
System.out.println(c.toString());
}
如果我们使用hasNext() 和next() 方法,看起来我们使用了两次while 循环。
当应用程序足够小并且性能是优先级时,这可以吗?还是可以优化代码?
【问题讨论】:
标签: java collections iterator