How to declare and initialize a List (ArrayList and LinkedList) with values in Java

Initializing a list while declaring is very convenient for quick use, but unfortunately, Java doesn't provide any programming constructs e.g. collection literals, but there is a trick which allows you to declare and initialize a List at the same time. This trick is also known as initializing List with values. If you have been using Java programming language for quite some time then you must be familiar with syntax of array in Java and how to initialize an array in the same line while declaring it as shown below:

String[] oldValues = new String[] {"list" , "set" , "map"};

or even shorter :

String[] values = {"abc","bcd", "def"};

Similarly, we can also create List  and initialize it at the same line, popularly known as initializing List in one line example. Arrays.asList() is used for that purpose which returns a fixed size List backed by Array. By the way don’t confuse between Immutable or read only List which doesn’t allow any modification operation including set(index) which is permitted in fixed length List.Here is an example of creating and initializing List in one line:

Java program to Create and initialize List in one line

How to create and initialize List in one line in Java with ArrayHere is a Java program which creates and initialize List in one line using Array. Arrays.asList() method is used to initialize List in one line and it takes an Array which you can create at the time of calling this method itself. Arrays.asList() also use Generics to provide type-safety and this example can be written using Generics as well.

import java.util.Arrays;
import java.util.List;

 * How to create and initialize List in the same line,
 * Similar to Array in Java.
 * Arrays.asList() method is used to initialize a List
 * from Array but List returned by this method is a
 * fixed size List and you can not change its size.
 * Which means adding and deleting elements from the
 * List is not allowed.
 * @author Javin Paul

public class ListExample {

    public static void main(String args[]) {
      //declaring and initializing array in one line
      String[] oldValues = new String[] {"list" , "set" , "map"};
      String[] values = {"abc","bcd", "def"};
      //initializing list with array in java
      List init = Arrays.asList(values);
      System.out.println("size: " + init.size()
                          +" list: " + init);
      //initializing List in one line in Java
      List oneLiner = Arrays.asList("one" , "two", "three");
      System.out.println("size: " + init.size()
                       +" list: " + oneLiner);
      // List returned by Arrays.asList is fixed size
      // and doesn't support add or remove

      // This will throw java.lang.UnsupportedOperationException

      // This also throws java.lang.UnsupportedOperationException

size: 3 list: [abc, bcd, def]
size: 3 list: [one, two, three]
Exception in thread "main" java.lang.UnsupportedOperationException
        at java.util.AbstractList.add(
        at java.util.AbstractList.add(
        at test.ExceptionTest.main(

As shown in above example it's important to remember that List returned by Arrays.asList() can not be used as regular List for further adding or removing elements. It's kind of fixed length Lists which doesn't support addition and removal of elements. Nevertheless its clean solution for creating and initializing List in Java in one line, quite useful for testing purpose.

If you want to convert that fixed length List into a proper ArrayList, LinkedList or Vector any other Collection class you can always use the copy constructor provided by Collection interface, which allows you to pass a collection while creating ArrayList or LinkedList and all elements from source collection will be copied over to the new List. This will be the shallow copy so beware, any change made on an object will reflect in both the list.

How to declare and initialize a List in one line

Here is how you can convert this fixed length list to ArrayList or LinkedList in Java:

package beginner;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

 * Java Program to create and initialize ArrayList LinkedList in same line
 * @author WINDOWS 8
public class HelloWorldApp {

    public static void main(String args[]) {
        List<String> pairs = Arrays.asList(new String[]{"USD/AUD", "USD/JPY", "USD/EURO"});
        ArrayList<String> currencies = new ArrayList<>(pairs);
        LinkedList<String> fx = new LinkedList<>(pairs);
        System.out.println("fixed list: " + pairs);
        System.out.println("ArrayList: " + currencies);
        System.out.println("LinkedList: " + fx);

fixed list: [USD/AUD, USD/JPY, USD/EURO]

This is pretty neat and I always this trick you create the Collection I want with values. You can use this to create ArrayList with values, Vector with values, or LinkedList with values. In theory, you can use this technique to create any Collection with values.

Related Java Collection tutorials from Javarevisited Blog
Related topics:


Sudhanshu said...

If you are using Google Collections aka Google Guava, you can initialize any kind of ArrayList in one line e.g. Integer, String, Double, Float, Long or any arbitrary type. Google Collection provides a utility class Lists, which has several factory method to return ArrayList of any type e.g.

List>Integer< listOfNumbers = Lists.newArrayList(1,2,3,4,5);

Anonymous said...

The ArrayList returned by Arrays.asList() is not your regular list, its a fixed length arraylist where you cannot add or remove elements, though you can replace elements using set() mehtod. If you want to create a regular ArrayList, just use a copy constructor like below

List mylist = new ArrayList((Arrays.asList(1,2 ,3,4));

this will create a fixed length list of integers and then copy content to a new regualr arraylist

Post a Comment