How to initialize an ArrayList in one line

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

package com.mkyong.common;
 
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
 
public class InitialArrayList {
 
	public static void main(String[] args) {
 
		//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);
		}
 
		//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);
		}
 
		//one line
		List<String> list3 =  new ArrayList<String>(
			Arrays.asList("String A", "String B", "String C")
		);  
 
		System.out.println("List 3......");
		for(String temp:list3){
			System.out.println(temp);
		}
 
	}
}
Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

  • http://www.digitalmodule.net bhavesh

    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

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

  • Paulo Italiano

    I find the 3rd way especially convenient.

    Best regards,
    Paulo

  • Tunki

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