javaseleniumselenium-webdriverwebdriverwindow-handles

Why getWindowHandles() in webdriver with java returns Set<> instead of ArrayList<>?


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?


Solution

  • 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.