Java Arrays asList()
java.util.Arrays.asList() method creates a fixed-size list.
The declaration of asList() method in java.util.Arrays class is
public static <T> List<T> asList(T... a)
From the definition, we can say that
- asList() is a static method.
- Return type of asList() is List. The type of items in the List is same as that of the elements passed as argument to the method.
- asList() does not throw any exception.
If there is any discrepancy with the type of elements, the method can cause a compilation error.
Example 1 – Arrays.asList() with Array as argument
In this example, we will take a string array, and convert it to List using asList() method.
Java Program
import java.util.Arrays; import java.util.List; public class Example { public static void main(String[] args) { String[] arr = {"apple", "banana", "cherry"}; List<String> list = Arrays.asList(arr); System.out.println(list); } }
Initialize string array arr
with three strings. Call Arrays.asList() method with arr passed as argument to it. Since, we have passed a string array, asList() method returns a List<String>.
Output
[apple, banana, cherry]
Example 2 – Arrays.asList() with Elements as Argument
You can also provide multiple elements to asList() method as arguments. The elements has to be separated by comma.
Java Program
import java.util.Arrays; import java.util.List; public class Example { public static void main(String[] args) { List<String> list = Arrays.asList("apple", "banana", "cherry"); System.out.println(list); } }
Call Arrays.asList() method and pass the elements as arguments. asList() method returns a List of type backed by the type of elements that we passed to it.
Output
[apple, banana, cherry]
Example 3 – Arrays.asList() with Class Objects
You can also provide elements of user defined class type to asList() method as arguments.
Java Program
import java.util.Arrays; import java.util.List; public class Example { public static void main(String[] args) { List<Car> list = Arrays.asList( new Car("BMW", 25), new Car("Toyota", 84), new Car("Tata", 19), new Car("Hundai", 37) ); System.out.println(list); } } class Car { public String name; public int units; public Car(String name, int units) { this.name = name; this.units = units; } public String toString() { return "(" + this.name + "," + this.units + ")"; } }
Call Arrays.asList() method and pass the objects as arguments. asList() method returns a List of type backed by the type of elements, which is Car in this example.
Output
[(BMW,25), (Toyota,84), (Tata,19), (Hundai,37)]
Conclusion
In this Java Tutorial, we learned how to use Arrays.asList() method of java.util package, to create a List from objects or an array, with the help of example programs.