Reputation: 121
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?
Upvotes: 3
Views: 5892
Reputation: 135802
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.
Upvotes: 4
Reputation: 121
Got the answer , findElements has return type as list and therefore the code worked after casting
ArrayList<WebElement> list=(ArrayList<WebElement>) driver.findElements(locator);
Upvotes: 0
Reputation: 16515
List is an Interface and ArrayList is an implementation. Similarly, List has other implementations too. So what driver.findElements(locator)
method returns may be some other implementation of List Interface. Of course, this is just an educated guess, as I don't know what findElements
method returns
Upvotes: 0