Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we use ArrayList to store WebElements?

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?

like image 504
Soumyansh Gupta Avatar asked Jun 18 '26 11:06

Soumyansh Gupta


1 Answers

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 use

Returns: 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.

like image 130
acdcjunior Avatar answered Jun 20 '26 00:06

acdcjunior