Main Tutorials

How to initialize an ArrayList in one line

Here’s a few ways to initialize an java.util.ArrayList, see the following full example:

InitArrayList.java

package com.mkyong.examples;

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

public class InitArrayList {

    public static void main(String[] args) {

        //1. Normal way
        List<String> list = new ArrayList<String>();
        list.add("String A");
        list.add("String B");
        list.add("String C");

        System.out.println("List 1......");
        for (String temp : list) {
            System.out.println(temp);
        }

        //2. Anonymous inner class
        List<String> list2 = new ArrayList<String>() {
            {
                add("String A");
                add("String B");
                add("String C");
            }
        };

        System.out.println("List 2......");
        for (String temp : list2) {
            System.out.println(temp);
        }

        //3. One line
        List<String> list3 = Arrays.asList("String A", "String B", "String C");

        System.out.println("List 3......");
        for (String temp : list3) {
            System.out.println(temp);
        }

    }

}

Output


List 1......
String A
String B
String C
List 2......
String A
String B
String C
List 3......
String A
String B
String C

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
7 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Alexsplosive
7 years ago

in one line Arrays.asList returns a list already.
So List list = Arrays.asList(“String A”, “StringB”); is enough

Prateek Ashtikar
9 years ago

Creating a private static final long serialVersionUID = 1L; is more appropriate work for 2nd suggested way!!

bhavesh
10 years ago

2nd Way is not appropriate in terms of performance.
courtesy of above line – http://stackoverflow.com/questions/924285/efficiency-of-java-double-brace-initialization

Thanks.

Ravi
10 years ago

Your posts are awesome, thanks for all your work and helping us.

Paulo Italiano
10 years ago

I find the 3rd way especially convenient.

Best regards,
Paulo

snag
10 years ago
Reply to  Paulo Italiano

Watch out for UnsoppertedOperationException when processing the list:
http://stackoverflow.com/questions/5755477/java-list-addobject-unsupportedoperationexception

Tunki
11 years ago

I LOVE YOUR WORK.
KEEP UP THE GOOD WORK!
THANK YOU SO MUCH MKYONG.
YOU ARE MY STAR!!!