Arrays asList() method in Java with Examples

The asList() method of java.util.Arrays class is used to return a fixed-size list backed by the specified array.

This method acts as bridge between array-based and collection-based APIs, in combination with Collection.toArray(). The returned list is serializable and implements RandomAccess.

This runs in O(1) time.



Syntax:

public static List asList(T... a)

Parameters: This method takes the array a which is required to be converted into a List.

Return Value: This method returns a list view of the specified array.

Below are the examples to illustrate the asList() method.

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate
// asList() method for String value
  
import java.util.*;
  
public class GFG1 {
    public static void main(String[] argv)
        throws Exception
    {
  
        try {
  
            // creating Arrays of String type
            String a[] = new String[] { "A", "B", "C", "D" };
  
            // getting the list view of Array
            List<String> list = Arrays.asList(a);
  
            // printing the list
            System.out.println("The list is: " + list);
        }
  
        catch (NullPointerException e) {
            System.out.println("Exception thrown : " + e);
        }
    }
}

chevron_right


Output:

The list is: [A, B, C, D]

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate
// asList() method for Integer value
  
import java.util.*;
  
public class GFG1 {
    public static void main(String[] argv)
        throws Exception
    {
  
        try {
  
            // creating Arrays of Integer type
            Integer a[] = new Integer[] { 10, 20, 30, 40 };
  
            // getting the list view of Array
            List<Integer> list = Arrays.asList(a);
  
            // printing the list
            System.out.println("The list is: " + list);
        }
  
        catch (NullPointerException e) {
            System.out.println("Exception thrown : " + e);
        }
    }
}

chevron_right


Output:

The list is: [10, 20, 30, 40]


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : olympusx



Article Tags :
Practice Tags :


2


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.