1

driver.getWindowHandles() returns Set so, if we want to choose window by index, we have to wrap Set into ArrayList:

var tabsList = new ArrayList<>(driver.getWindowHandles());
var nextTab = tabsList.get(1);
driver.switchTo().window(nextTab);

in python we can access windows by index immediately:

next_window = browser.window_handles[1]
driver.switch_to.window(next_window)

What is the purpose of choosing Set here?

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
keran
  • 113
  • 1
  • 5

3 Answers3

2

Window Handles

In a discussion, regarding Simon (creator of WebDriver) clearly mentioned that:

While the datatype used for storing the list of handles may be ordered by insertion, the order in which the WebDriver implementation iterates over the window handles to insert them has no requirement to be stable. The ordering is arbitrary.


Background

In the discussion What is the difference between Set and List? @AndrewHare explained:

List<E>:

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.

Set<E>:

A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. As implied by its name, this interface models the mathematical set abstraction.


Conclusion

So considering the above definition, in presence of multiple window handles, the best possible approach would be to use a Set<>


References

You can find a couple of working examples in:

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
2

Because Sets do not impose an order,* which is important since there is no guaranteed order of the window handles returned. This is because the window handles represent not only tabs but also tabs in other browser windows. There is no reliable definition of their overall order which would work across platforms and browsers, so a List (which imposes order) wouldn’t make much sense.

* Technically, SortedSet is a subtype of Set which does impose an order, but the general contract of Set does not require any order.

VGR
  • 40,506
  • 4
  • 48
  • 63
0

One comment - take into account the order of Set is not fixed, so it will return you a random window by the usage above.

eyalka
  • 21
  • 5