Why is Arrays.asList() used in Java?
If you have an Array that you need to turn into a list then java.util.Arrays provides a wrapper Arrays.asList() to serve this purpose. In simple words, this method takes an array as a parameter and returns a list. Major portions of the Java platform API were developed before the collections framework was introduced. So occasionally, you might need to translate between traditional arrays and the more modern collections. This function serves as a link between Collections and Array based API’s.![Arrays.asList() Method in Java - 1](https://cdn.codegym.cc/images/article/e0aa7c88-8294-4004-ab28-6c7cc1b4c354/800.jpeg)
Example
Have a look at the following example:
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
public class ArraysAsListDemo {
public static void main(String[] args) {
String[] teamMembers = {"Amanda", "Loren", "Keith"};
// using aslist() method
List teamList = Arrays.asList(teamMembers);
System.out.println("List : " + teamList);
HashSet teamHashSet = new HashSet<>(Arrays.asList(teamMembers));
System.out.println("HashSet : " + teamHashSet);
}
}
Output:
How Arrays.asList() and ArrayList are different?
When you call the Arrays.asList() method on an array, the returned object is not an ArrayList (A resizable array implementation of List interface). It is a view object with get() and set() methods that access the underlying array. All methods that would change the size of the array such as the add() or remove() of the associated iterator throw an UnsupportedOperationException. The reason java program compiles successfully but gives a Runtime Exception is that, apparently, a “List” is returned as result of Arrays.asList(). Where all the addition/deletion operations are permissible. But since, the underlying data structure is a non-resizable “array”, hence an exception is thrown at the run time. Here’s a snippet showing how it looks like:
import java.util.Arrays;
import java.util.List;
public class ArraysAsListDemo {
public static void main(String[] args) {
Integer[] diceRoll = new Integer[6];
//using aslist() method
List diceRollList = Arrays.asList(diceRoll);
System.out.println(diceRollList);
// using getters and setters to randomly access the list
diceRollList.set(5, 6);
diceRollList.set(0, 1);
System.out.println(diceRollList.get(5));
System.out.println(diceRollList.get(1));
System.out.println(diceRollList);
diceRollList.add(7); // Add a new Integer to the list
}
}
Output:
Examples for using asList() method
As of Java SE 5.0, the asList() method is declared to have a variable number of arguments. Instead of passing an array, you can also pass individual elements. For example:
import java.util.Arrays;
import java.util.List;
public class ArraysAsListDemo {
public static void main(String[] args) {
List seasons = Arrays.asList("winter", "summer", "spring", "fall");
List odds = Arrays.asList(1, 3, 5, 7, 9);
System.out.println(seasons);
System.out.println(odds);
}
}
Output:
Advanced Use Cases of Arrays.asList()
in Test Automation
The Arrays.asList()
method in Java is often used to convert arrays into lists. While its typical use is straightforward, it can play a critical role in test automation frameworks by improving code organization, flexibility, and efficiency. This section explores advanced scenarios where Arrays.asList()
enhances test automation practices.
1. Managing Driver Instances with Arrays.asList()
In test automation frameworks, managing multiple browser driver instances is essential for cross-browser testing. Using Arrays.asList()
, you can easily create and manage a collection of driver instances, improving the scalability of your tests.
Example: Managing Multiple Browser Instances
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.List;
import java.util.Arrays;
public class DriverManagement {
public static void main(String[] args) {
WebDriver chromeDriver = new ChromeDriver();
WebDriver firefoxDriver = new FirefoxDriver();
// Creating a list of driver instances
List<WebDriver> drivers = Arrays.asList(chromeDriver, firefoxDriver);
// Iterating over drivers to perform actions
for (WebDriver driver : drivers) {
driver.get("https://example.com");
System.out.println("Current URL: " + driver.getCurrentUrl());
}
// Closing all driver instances
drivers.forEach(WebDriver::quit);
}
}
This approach simplifies handling multiple driver instances by storing them in a single list, making it easier to iterate, perform actions, and manage resources.
2. Validating URL Redirections with Arrays.asList()
URL redirection validation is a common task in web testing. Arrays.asList()
can help parameterize the source and target URLs, allowing for efficient validation using a loop.
Example: URL Redirection Validation
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.List;
import java.util.Arrays;
public class URLRedirectionTest {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
// Source and target URLs
List<String> sourceUrls = Arrays.asList("http://example.com/page1", "http://example.com/page2");
List<String> targetUrls = Arrays.asList("http://example.com/redirect1", "http://example.com/redirect2");
for (int i = 0; i < sourceUrls.size(); i++) {
driver.get(sourceUrls.get(i));
String currentUrl = driver.getCurrentUrl();
if (currentUrl.equals(targetUrls.get(i))) {
System.out.println("Redirection validated for: " + sourceUrls.get(i));
} else {
System.out.println("Redirection failed for: " + sourceUrls.get(i));
}
}
driver.quit();
}
}
This method ensures all redirections are validated efficiently by leveraging the list structure provided by Arrays.asList()
.
3. Managing Web Elements with Arrays.asList()
Web elements often need to be grouped and processed together in test automation. Arrays.asList()
offers a convenient way to collect elements into a list for bulk operations.
Example: Handling Web Elements
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.List;
import java.util.Arrays;
public class WebElementManagement {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://example.com");
// Locating multiple elements
WebElement element1 = driver.findElement(By.id("button1"));
WebElement element2 = driver.findElement(By.id("button2"));
WebElement element3 = driver.findElement(By.id("button3"));
// Creating a list of elements
List<WebElement> elements = Arrays.asList(element1, element2, element3);
// Clicking each element
elements.forEach(WebElement::click);
driver.quit();
}
}
This approach simplifies managing a group of related web elements, enabling clean and concise code for repetitive operations.
GO TO FULL VERSION