When to use Set and when List in selenium?
I am literally confused always.
I know whenever we work with multiple windows then we use SET for example
Set <String> allwindows = driver.getwindowhandles();
Iterator <String> it = allWindows.iterator();
In case of select or check all checkboxes we use List <WebElement> for example
List <WebElement> checkbox = driver.findElements(By.xpath(“//input[@type=’checkbox’]”));
When to use SET and LIST can somebody clarify ?
Set and List are two interface to a collection data structure.
The question that you have asked is very good. .getWindowHandles returns a set. This is because Set’s basic requirement is that it only stores unique elements. Window handles has to be unique. Duplicate elements are not allowed in sets.
.findElements return a list because lists preserves the order. That means that the order in which elements were found on the page are preserved in the List. Hence user gets the list of element in exact order in which the elements were found in HTML dom.
I hope that clears your doubt?
List is an ordered sequence of elements whereas Set is a distinct list of elements which is unordered. Conceptually we usually refer to an unordered grouping that allows duplicates as a Bag and doesn’t allow duplicates is a Set.
An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.
Unlike sets, lists in Java typically allow duplicate elements. More formally, lists typically allow pairs of elements e1 and e2 such that e1.equals(e2), and they typically allow multiple null elements if they allow null elements at all. It is not inconceivable that someone might wish to implement a list that prohibits duplicates, by throwing runtime exceptions when the user attempts to insert them, but we expect this usage to be rare.