Seems to me that driver.getWindowHandles() does not work for tabs... you'll always get back a one item array with the CURRENT tab's handle... [deleted old answer as this seems to be fixed now]
UPDATE (6/16/2016): the current version of Selenium (server standalone 2.53.0) seems to act differently. Now I'm using something like this to open/switch the driver to the new tab:
UPDATE (11/16/2016): Selenium 3.0.1 seems to have changed things again? I have to use javascript to open a new tab now. This seems to work in Chrome only... Firefox opens a new window. I'm going to see if that behavior can be changed using geckodriver's settings (capabilities/profile?).
// Actions actions = new Actions(driver);
// actions.keyDown(Keys.CONTROL).sendKeys("t").keyUp(Keys.CONTROL).build().perform();
((JavascriptExecutor)driver).executeScript("window.open('about:blank', '_blank');");
Set<String> tab_handles = driver.getWindowHandles();
int number_of_tabs = tab_handles.size();
int new_tab_index = number_of_tabs-1;
driver.switchTo().window(tab_handles.toArray()[new_tab_index].toString());
the getWindowHandles() method is now returning a Set. This has only been tested in Chrome so far, since Firefox version 47 currently has some serious problems using the firefoxdriver... and using geckodriver the Actions aren't working at all. [update 6/11/2016]: Firefox through geckodriver now returns a Set]
You can also do something like this.. cast it to ArrayList:
// set tab_index to the number of window/tab you want. 0 is the first tab
ArrayList<String> tabs_windows = new ArrayList<String> (driver.getWindowHandles());
driver.switchTo().window(tabs_windows.get(tab_index));
Update: To get around the geckodriver bug, I've switched to using element.sendkeys... something like this seems to work in Marionette and Chrome.. (Update2): Updated to javascript because of changes in Selenium 3.0.1:
// driver.findElement(By.cssSelector("body")).sendKeys(Keys.chord(Keys.CONTROL, "t"));
((JavascriptExecutor)driver).executeScript("window.open('about:blank', '_blank');");
Set<String> tab_handles = driver.getWindowHandles();
int number_of_tabs = tab_handles.size();
int new_tab_index = number_of_tabs-1;
driver.switchTo().window(tab_handles.toArray()[new_tab_index].toString());
UPDATE (11/16/2016): the old method to close using Ctrl-W seems to be broken, too... use this:
((JavascriptExecutor)driver).executeScript("close();");