Below code works fine when i use List instead of ArrayList,
ArrayList<WebElement> list= driver.findElements(locator);
I want to understand why I can't use ArrayList here? Is it used to store specific type of elements?
WebDriver#findElements(...) returns a java.util.List:
java.util.List<WebElement> findElements(By by)Find all elements within the current page using the given mechanism. This method is affected by the 'implicit wait' times in force at the time of execution. When implicitly waiting, this method will return as soon as there are more than 0 items in the found collection, or will return an empty list if the timeout is reached.
Parameters:
by- The locating mechanism to useReturns: A list of all
WebElements, or an empty list if nothing matches
Knowing that List is an interface and ArrayList is a concrete implementation (class) of that interface, the documentation does not specify if the List returned is an ArrayList or not. If it were you could simply cast it to ArrayList.
So, since the concrete type is unknown...
...if you want an ArrayList, you have to construct one from the list returned:
ArrayList<WebElement> list = new ArrayList<>(driver.findElements(locator));
That's the only reliable method. Casting may work for some driver implementations but not for others.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With