我想了解迭代器設計模式,並在以下教程中找到。迭代java集合的性能高效方法是什麼?
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循環兩次。
當應用程序足夠小並且性能優先時,這是否正確?或者可以有優化的代碼?
感謝@Tagir Valeev的解釋,現在我真的好奇hasNext()和next()如何在Java集合中工作? –
@AMY,檢查Java源代碼。例如,[這裏是](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/java/util/ArrayList.java#845)ArrayList迭代器。 –
是的,我經歷了你建議的鏈接。 hasNext()方法中的代碼「return cursor!= size;」清除所有疑慮。 –