简体   繁体   中英

ListIterator or Iterator does not stop at the end of the List

I am storring the multiple elements (17 to be specific) into 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.

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

Element at position 1329909

Element at position 1329910

Element at position 1329911

Element at position 1329912

Element at position 1329913

As you do not consume the elements from iterator - the cursor for this iterator is not moved and hasNext is always true. You should call ListIterator::next in your loop :

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

From ListIterator::next docs :

Returns the next element in the list and advances the cursor position.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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