Arrays.asList() is a useful method in Java, which is part of the java.util.Arrays class. This method is used to return a fixed-size list backed by the specified array. In this way, it acts as a bridge between array-based and collection-based APIs, along with Collection.toArray(). The returned list is serializable and implements RandomAccess, making it a useful tool for data manipulation.
The syntax of the asList() method is straightforward. It takes an array a, which is required to be converted into a List, as a parameter, and returns a list view of the specified array.
Let's look at some examples of how this method works in Java:
Example 1: Working of asList() method in Java
javaimport java.util.*;
public class Example1 {
public static void main(String[] args)
{
String arr[] = { "GfG", "IDE", "Courses"};
List<String> list = Arrays.asList(arr);
System.out.println(list);
}
}
Output:
[GfG, IDE, Courses]
Example 2: Internal working of asList() method in Java
javaimport java.util.*;
public class Example2 {
public static void main(String[] args)
{
String arr[] = {"GfG", "IDE", "Courses"};
List<String> list = Arrays.asList(arr);
arr[0] = "Practice";
System.out.println(list);
list.set(1, "Premium");
System.out.println(Arrays.toString(arr));
}
}
Output:
[Practice, IDE, Courses]
[Practice, Premium, Courses]
One important thing to note is that the list returned by the asList() method is a fixed size, and nothing can be added or removed from the list in Java.
However, there are several practical applications of the asList() method in Java, such as reversing a list or creating a collection from the array elements. Let's take a look at some examples:
Reversing a list
javaimport java.util.*;
public class Example3 {
public static void main(String[] args)
{
String arr[] = {"GfG", "IDE", "Courses"};
Collections.reverse(Arrays.asList(arr));
System.out.println(Arrays.toString(arr));
}
}
Output:
[Courses, IDE, GfG]
Creating a Collection from the array elements
javaimport java.util.*;
public class Example4 {
public static void main(String[] args)
{
String arr[] = {"GfG", "IDE", "Courses"};
HashSet<String> s
= new HashSet<String>(
Arrays.asList(arr));
System.out.println(s);
}
}
Output:
[GfG, Courses, IDE]
In conclusion, the asList() method in Java is an efficient way of converting an array into a fixed-size list. It has many practical applications, such as reversing a list or creating a collection from the array elements. By understanding how this method works and how to use it, you can save yourself time and effort in your Java programming.