How To Use Arrays.asList() In Java [With Examples]

Arun Gupta

Posted On: June 16, 2023

view count145439 Views

Read time11 Min Read

Test automation can be quite challenging sometimes when dealing with complex test cases. Although there are multiple ways available in any programming language to solve a particular problem, you need to be vigilant that your solution follows the best and the most efficient coding practices.

A fundamental yet important approach while designing an automation testing framework is the parameterization of data-driven test cases. A data-driven test case can be invoked multiple times with a different set of data values, which are passed as arguments to the parameters defined in the test method to achieve parameterization.

Talking about Java as the programming language for automation testing, there are many ways available in which you can parameterize your tests with tools like Selenium WebDriver, Appium, etc. But there is one method that can primarily be used for this purpose: Arrays.asList() method.

Arrays.asList() in Java is an important method that acts as a bridge between the array and collection interface in Java and provides many ways to implement parameterization.

In this blog on Arrays.asList() in Java, we will explore how the Arrays.asList() in Java works and provide examples to illustrate its usage. Whether you’re a beginner or a seasoned Java developer, understanding Arrays.asList() in Java can make your coding more efficient and productive.

So, let’s dive in!

What is Arrays.asList() in Java?

A Java array is a fixed-size data structure that stores elements of the same data type. As an object, it’s assignable to variables, passable as method parameters, and returnable from methods, providing a versatile means of handling sequences in Java programming.

The Arrays.asList() in Java can be used in multiple ways where you can pass an array, elements, and objects as arguments to the method. Let’s first understand its syntax and usage with the help of simple code examples. Post that, we’ll discuss the real-time examples related to test automation using Selenium with Java.

Syntax:

arrays as list

  • public is an access modifier.
  • static is a non-access modifier.
  • List is the method object return type.
  • asList is the method name.
  • a is a method argument.

Arrays.asList() method examples

There are three ways in which you can use the Arrays.asList() in Java to implement parameterization by passing different argument types and then converting them into a list.

Array as an argument

The Arrays.asList() in Java can accept an array as an argument and convert it to a list. The array passed as an argument to the method must be of Wrapper Class type (Integer, Float, etc.) instead of primitive data type (int, float, etc.).

Output:

Array as an argument output

In this example, a String type array has been passed as an argument to the Arrays.asList() in Java for converting the array to a list of string elements.

Info Note

Test your Java automated scripts across 3000+ browser environments. Try LambdaTest Now!

Elements as an argument

Instead of passing the array, you can pass multiple comma-separated elements as arguments to the Arrays.asList() method.

Output:

Elements as an argument output

In the example shown above, multiple String type elements are directly passed as arguments to the method for converting them as a list of string elements.

Objects as an argument

There could be certain scenarios where you must create a list of objects of a self-defined class and then perform some action on that list.

The Arrays.asList() in Java allows you to pass class objects as arguments. It then creates a list of the objects you can use to perform specific actions.

In the ProgrammingLanguage class shown above, we are initializing the instance variables with the help of the constructor and overriding the toString() method to represent the objects in string form.

Output:

Objects as an argument output

In the class above, we are passing the objects of the ProgrammingLanguage class to the asList() method as arguments to get a list of these objects.

Arrays.asList() method usage in test automation

In this section of the Selenium Java tutorial, we will discuss the real-time examples in which we can use the Arrays.asList() in Java to parameterize our test cases.

Handling different driver instances

The basic capability of a UI testing framework is to execute the test cases on different browsers or platforms. This can be easily achieved using the concept of parameterization in the TestNG framework.

Feel free to choose any framework you are comfortable working with to implement the logic of handling multiple browsers. TestNG is one option, but if you are not familiar with it or prefer another framework, you can explore other alternatives.

The Arrays.asList() in Java can be used predominantly for this purpose. Assuming Selenium WebDriver as the automation testing tool in this example, we will see how we can write a logic for handling multiple driver instances for different browsers using the Arrays.asList() method.

gituhb

You will see that a list of browser names has been initialized with the help of the Arrays.asList() in Java. This list is then iterated through a for-each loop to instantiate the driver class of the respective browser.

You can run the tests on LambdaTest, a unified digital experience testing platform that allows you to perform Java automation testing on an online Selenium Grid across 3000+ browsers and real devices. You can generate automation capabilities for your tests via the LambdaTest capabilities generator. The code snippets of the capabilities, which are automatically generated using the capabilities generator, have been included in the test code above for reference.

Subscribe to our LambdaTest YouTube Channel for live updates with the latest tutorials around Selenium testing, Cypress testing, and more.

Validating multiple URL redirects

A very interesting scenario that I came across in one of my previous projects was to validate a security checklist that contained a list of URLs and their expected redirected URLs.

This list was huge and contained many URLs. The best way to test this scenario was to parameterize a test method with these URLs as arguments and open all of them one by one in the browser to check the redirected URL.

Although I used an Excel sheet as a data source for this test scenario, here I will try to provide a simplified code example using the Arrays.asList() method, which will take the URLs as arguments and print the redirected URLs on the console.

Output:

Validating multiple URL redirects

To gain access to these URLs, register for a free account and log in to your LambdaTest account.

Post logging in, you can see that this code is simply converting the array of URLs into a list using the Arrays.asList() method and then iterating the list using a for-each loop to open all the URLs one by one in the browser. Once the URLs are loaded, the current page URL is extracted and printed on the console.

Handling multiple web elements

There are certain scenarios in which you need to handle web elements at once to validate some functionality. A good example of such a scenario is to validate that there are no broken links or images on a webpage.

To build the logic for this scenario, you first need to collect all the links and then hit them one by one to check if the server is returning a 404 response code. The Arrays.asList() in Java again comes in handy here and does the job easily.

Here’s a code example for this.

Output:

Handling multiple web elements

As you can see in this code example, all img elements present on the test URL are first collected into a list, and then their src URLs are extracted and hit one by one to assert the response code. All the URLs which returned 404 as a response code are added to another list, and then this list is printed on the console. There are currently two broken images available on this test URL, and the src URLs of both are printed in the console.

Bonus: Arrays.asList vs. new ArrayList(Arrays.asList())

Arrays.asList() and new ArrayList<>(Arrays.asList()) are two different ways of creating a List from an array in Java. Let’s discuss them in detail.

Arrays.asList()

Arrays.asList() in Java creates a list backed by the original array. This means that any changes made to the list will be reflected in the original array and vice versa. The resulting list is fixed-size and cannot be resized. If you need a mutable list, you need to create a new list based on the original list.

Mutable in Java refers to those objects whose state can be changed after they are created. In this case, a mutable list is a list that can be resized by adding or removing the elements. On the other hand, an immutable list is a list in which no structural changes can be made.

Below is the code example to demonstrate that any changes made to the list will also be reflected in the original array.

Output:

Arrays.asList()

Here you can see that the value of the third index of the list has been changed to “C++” from “Ruby” and when the original array was printed on the console, it also reflected the change.

The second example shown below is to prove that the list created using the Arrays.asList() in Java is immutable.

Output:

array output

Here you can see that the program had thrown an UnsupportedOperationException when an attempt at the structural modification of the list was made using the add() method.

new ArrayList(Arrays.asList())

On the other hand, new ArrayList<>(Arrays.asList()) creates a new ArrayList based on the elements of the array. This means any changes to the new list will not affect the original array and vice versa. The resulting list is mutable and can be resized.

In the example above, the list has been modified successfully.

Output:

new ArrayList(Arrays.asList())

Conclusion

The Arrays.asList() in Java works as a bridge between the array and the collection interface. It converts an array into a fixed-size list, and any changes made to the values of the list elements will be reflected in the original array and vice versa.

This is a convenient method to implement parameterization in your tests, especially when you are not using other supporting libraries like TestNG in your framework.

Throughout this blog, we explored the syntax and usage of the Arrays.asList() in Java and provided examples to demonstrate its functionality.

Frequently Asked Questions (FAQs)

What is the asList() method of ArrayList in Java?

The asList method returns an ArrayList of a different type from Java’s util. ArrayList. The primary distinction is that the resulting ArrayList acts as a wrapper for an existing array; the add and remove functions are not included.

What type of list is Arrays.asList()?

asList returns a fixed-size list backed by the specified array; the returned list is serializable and allows random access.

Author Profile Author Profile Author Profile

Author’s Profile

Arun Gupta

Arun is an ISTQB Certified Tester with over 11 years of work experience in Manual and Automation testing with Agile practices. He has good experience in creating highly flexible and reliable automation frameworks using the capabilities of Selenium WebDriver, Java, TestNG, Cucumber etc.

Blogs: 2



linkedintwitter