我将多个元素(具体为 17 个)存储到 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++;
}
输出是这样的。
...
位置 1329908 处的元素
位置 1329909 处的元素
位置 1329910 处的元素
位置 1329911 处的元素
位置 1329912 处的元素
位置 1329913 处的元素
最佳答案
由于您不使用迭代器中的元素 - 该迭代器的光标不会移动,并且 hasNext
始终为 true。您应该在循环中调用 ListIterator::next
:
ListIterator<WebElement> ele = Categories.listIterator();
while(ele.hasNext()) {
WebElement element = ele.next();
// do something with your element
}
来自ListIterator::next
文档:
Returns the next element in the list and advances the cursor position.
关于java - ListIterator 或 Iterator 不会在 List 末尾停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57902365/