简体   繁体   中英

Java enhanced for loop and IndexOutOfBoundsException?

How come that I am getting IndexOutOfBoundsException while using Java enhanced for loop?My code looks like this

for (WebElement input : driver.findElements(By.cssSelector("input[type='text']"))) {
    if (input.isDisplayed()) {
        input.clear();
    }
}

It uses Selenium WebDriver to find all <input type="text" /> tags and clear they content if they are displayed (otherwise it would throw a different exception). And in some tests I get

java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
    at java.util.ArrayList.rangeCheck(ArrayList.java:604)
    at java.util.ArrayList.get(ArrayList.java:382)

Rest of the stack trace is on Pastebin .

EDIT

This error still occurs even if I add the check for array emptiness

List<WebElement> inputs = driver.findElements(By.cssSelector("input[type='text']"));
if (!inputs.isEmpty()) {
     for(WebElement input : inputs) {
     }
}
    java.lang.IndexOutOfBoundsException: Index: 1, Size: 0

This specifies that you have entered the loop, at index 1, although the size of the array is 0. You should enter at index 0. Which is strange. So this would indicate that the error is being thrown by see below


Try and run some debugging - Before this, try and print the object which is returned by

    driver.findElements(By.cssSelector("input[type='text']"))

and try and see if anything is actually returned.

I would have commented but don't have enough rep.

Also it's a for-each loop.

Can you check the result of this statement driver.findElements(By.cssSelector("input[type='text']")) .

It seems driver.findElement s is getting indexOutOfBound exception even before enhanced loop start to execute. Can you try to debug or print the value on console.

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