使用迭代器时如何确定最后一个元素?

Joh*_*ood 7 java iterator

我喜欢使用迭代器原理的for循环,比如

for(String s : collectionWithStrings)
    System.out.println(s + ", ");
Run Code Online (Sandbox Code Playgroud)

问题:如何确定当前元素是否是最后一个元素?

有这样的自己的索引int = 0; i < collection.size(); i++是可能的i == collection.size() - 1,但不是很好.对于上面的例子,是否也可以用迭代器确定最后一个元素?

Fri*_*itz 8

实际上,该Iterator#hasNext方法返回一个布尔值,确定迭代器是否将返回该next方法的另一个元素.

你的迭代可以这样:

Iterator<String> iterator = collectionWithString.iterator();
while(iterator.hasNext()) {
    String current = iterator.next();
    // if you invoke iterator.hasNext() again you can know if there is a next element
}
Run Code Online (Sandbox Code Playgroud)


ada*_*shr 5

只需使用该hasNext方法.

if(!iterator.hasNext()) {
    // this is the last element
}
Run Code Online (Sandbox Code Playgroud)

通常,我们使用Iteratoras 迭代:

while(iterator.hasNext()) {
    Object obj = iterator.next();
}
Run Code Online (Sandbox Code Playgroud)