简体   繁体   中英

How is List<WebElement> interface being implemented when I use findElements?

List is an interface. List<String> list=new ArrayList<String>(); Here, lets say we are creating a reference variable of list interface and assigning it to the ArrayList object which implemets List interface.

Lets say if we want to get the size of the list. We will use list.size() which will internally invoke the size() method of ArrayList object using Runtime Polymorphism.

Simply here what I mean to say is the methods of List is implemented in ArrayList class thats why we are able to use it.

Question is,

How I am able to use size() and how the size method is being implemented in what Class ?

List<WebElement> noOfRows=driver.findElements(By.xpath(".//*[@id='leftcontainer']//tbody/tr"));
List<WebElement> noOfCol=driver.findElements(By.xpath(".//*/tr/th"));

int rowSize=noOfRows.size();
int colSize=noOfCol.size();

I hope you guys are getting my point.

When I say List<String> list= new ArrayList<String>(); That means I am going to use ArrayList methods as runtime polymorphism.

But what in this case...

driver.get("https://money.rediff.com/gainers/bse/daily/groupa?src=gain_lose");

List<WebElement> noOfRows=driver.findElements(By.xpath(".//*[@id='leftcontainer']//tbody/tr"));
List<WebElement> noOfCol=driver.findElements(By.xpath(".//*/tr/th"));


int rowSize=noOfRows.size();//How I am able to use method of a List interface
int colSize=noOfCol.size();

I am able to run the program and do everything but just want to clear the concept here . Seems like I am confused on a minor issue but want this confusion to be gone. Thankyou in advance

A variable in Java can have a type List , but it is not possible to instantiate the List interface, that is, to create an object of type List in memory. The objects in memory are of some other type that implements the List interface.

The object returned from findElements implements the interface List , but the actual class of that object is unknown to the compiler. You can query it at runtime, by using the getClass method, but that is usually not necessary because you can treat it as a List without having to know exactly what kind of List it is.

When you call size on the List returned by findElement , the JVM selects the correct size implementation to use based on the actual type of the object. So if it just happens to be an ArrayList then you'll get ArrayList.size , etc. Often the type of List returned from a method like this isn't one of the usual types from java.util but some custom implementation that is tailored to the task at hand.

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