Wednesday, June 29, 2022

How to declare and initialize a List with values in Java (ArrayList/LinkedList) - Arrays.asList() Example

Hello guys, today, I am going to share with you a useful tip to initialize a List like ArrayList or LinkedList with values, which will help you a lot while writing unit tests and prototypes. Initializing a list while declaring is very convenient for quick use, but unfortunately, Java doesn't provide any programming constructs like the collection literals of Scala, but there is a trick which you can use to declare and initialize a List at the same time. This trick is also known as initializing a List with values. I have used this trick a lot while declaring list for unit testing and writing demo programs to understand an API etc and today I'll you'll also learn that.

If you have been using Java programming language for quite some time then you must be familiar with the syntax of an 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 a 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, but there are some problems with that as you cannot add or remove elements on that list.

By the way, don’t get confused between Immutable or read-only List which doesn’t allow any modification operation including set(index) which is permitted in fixed-length List. You can further see a good Java course like The Complete Java Masterclass to learn more about the Immutable list in Java.




Java program to Create and initialize List in one line

Now that we know how to create and initialize the list at the same line, let's see an example of how to use this trick in a Java program. Here is a Java program that creates and initializes List in one line using Array.

The 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. It also uses Generics to provide type-safety and this example can be written using Generics as well.

But the drawback is that it returns a fixed size ArrayList which means you cannot add and remove elements if you want. You can overcome that limitation by creating another ArrayList by copying values from this list using copy constructor as shown below.

If you want to learn more about the Collection and ArrayList class, see Java Fundamentals: Collections course on Pluralsight, one of the specialized course on Collections.

How to create and initialize List in one line in Java with Array



And here is the complete Java program to show this in action:

Arrays.asList() Example


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

/**
 * 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 an 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
      oneLiner.add("four"); 


      // This also throws java.lang.UnsupportedOperationException
      //oneLiner.remove("one"); 
    }
}

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


As shown in the above example it's important to remember that List returned by Arrays.asList() can not be used as a regular List for further adding or removing elements.

It's kind of fixed length Lists which doesn't support the addition and removal of elements. Nevertheless its clean solution for creating and initializing List in Java in one line, quite useful for testing purposes.

If you want to convert this fixed length List into a proper ArrayList, LinkedList or Vector any other Collection class you can always use the copy constructor provided by the Collection interface, which allows you to pass a collection while creating ArrayList or LinkedList and all elements from the 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. You can read more about shall and deep cloning in Java on The Complete Java Masterclass course on Udemy. One of my recommended course to all Java programmers.

Here is also a summary of how to create a list with values in Java:

How to declare and initialize a List in one line




Arrays.asList() to ArrayList in Java

And, here is a sample Java program which will show you  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);
    }
}

Output:
fixed list: [USD/AUD, USD/JPY, USD/EURO]
ArrayList: [USD/AUD, USD/JPY, USD/EURO]
LinkedList: [USD/AUD, USD/JPY, USD/EURO]

That's all about how to declare and initialize a list with values in Java.  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.




Other ArrayList tutorials for Java Programmers
  • How to remove duplicate elements from ArrayList in Java? (tutorial)
  • Top 5 courses to learn Java Collections and Streams (best courses)
  • How to loop through an ArrayList in Java? (tutorial)
  • 10 Advanced Core Java Courses for Programmers (advanced courses)
  • How to synchronize an ArrayList in Java? (read)
  • Top 5 Courses to become full-stack Java developers (online courses)
  • How to create and initialize ArrayList in the same line? (example)
  • Top 5 Java Concurrency and thread courses (best courses)
  • When to use ArrayList over LinkedList in Java? (answer)
  • Top 5 Courses to learn Spring MVC for beginners (spring courses)
  • Difference between ArrayList and HashMap in Java? (answer)
  • 10 Best Spring Boot Courses for Java developers (boot courses)
  • Difference between ArrayList and Vector in Java? (answer)
  • 10 Free Spring Courses for Java programmers (Free courses)
  • How to sort an ArrayList in descending order in Java? (read)
  • Difference between ArrayList and HashSet in Java? (answer)
  • Difference between an Array and ArrayList in Java? (answer)
  • How to reverse an ArrayList in Java? (example)
  • How to get a sublist from ArrayList in Java? (example)
  • How to convert CSV String to ArrayList in Java? (tutorial)

Thanks for reading this article so far. If you like this article then, please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.

P.S, - If you are new to the Java world and looking to self-teach Java to yourself, here is a list of some Free Java courses for Beginners from Udemy, Coursera, and Pluralsight you can join to learn Java online.

3 comments:

  1. 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);

    ReplyDelete
  2. 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

    ReplyDelete
  3. Out of several ways, I think Arrays.asList() + Copy Constructor is best way to initialize ArrayList inline in Java.

    ReplyDelete