简体   繁体   English

ListIterator或Iterator不会在列表末尾停止

[英]ListIterator or Iterator does not stop at the end of the List

I am storring the multiple elements (17 to be specific) into List. 我将多个元素(具体是17个)存储到List中。 and I am trying to iterate through it and print something. 我正在尝试遍历并打印一些内容。 But When I checked, the iterator .hasNext() is not stopping at the end of the List. 但是,当我检查时,迭代器.hasNext()并未在列表末尾停止。

List<WebElement> Categories = driver.findElements(By.xpath("//h2[@class='popover-category-name']"));

ListIterator<WebElement> ele = Categories.listIterator();
int i=0;
while(ele.hasNext()) {
    //String eleText = Categories.get(i).getText();
    System.out.println("Element at position "+i+" ");
    i++;
}

Output is coming like this. 输出是这样的。

... ...

Element at position 1329908 元素在位置1329908

Element at position 1329909 元素在位置1329909

Element at position 1329910 位置1329910的元素

Element at position 1329911 位置1329911的元素

Element at position 1329912 位置1329912的元素

Element at position 1329913 位置1329913的元素

As you do not consume the elements from iterator - the cursor for this iterator is not moved and hasNext is always true. 由于您不使用迭代器中的元素-该迭代器的光标不会移动,并且hasNext始终为true。 You should call ListIterator::next in your loop : 您应该在循环中调用ListIterator::next

ListIterator<WebElement> ele = Categories.listIterator();
while(ele.hasNext()) {
    WebElement element = ele.next();
    // do something with your element
}

From ListIterator::next docs : ListIterator::next docs:

Returns the next element in the list and advances the cursor position. 返回列表中的下一个元素并前进光标位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM