就像在 C++ 中一样,我们有 end() ,其中迭代器结束于最后一个元素之后的位置,对于 Java 迭代器来说是真的吗?
while (iterator.hasNext()) {
String color = iterator.next();
}
Run Code Online (Sandbox Code Playgroud)
例如在 C++ 中,我们有:
Blue Green Purple
^ ^ ^ ^
begin end
Run Code Online (Sandbox Code Playgroud)
我将如何在 Java 思维/术语中绘制上述插图?
In Java, Iterator is an interface meaning that there has to be a concrete class implementing the methods of the interface. Now that depends on the type of collection that is used. As an example, to iterate on a collection of the type List, we use a ListIterator.
For a listIterator, there is no current element that it holds. The cursor position would lie between elements, at the beginning of the collection or at the end of the last element in the list. The illustration should make it more clear.
So, when hasNext() returns false, you know you are at the end of the Collection (List, in our case) which throws a NoSuchElementException.
| 归档时间: |
|
| 查看次数: |
2300 次 |
| 最近记录: |