How to Initialize an ArrayList in One Line in Java


In this example, we will learn two methods to create a list object in Java.

Source Code

1)

package com.beginner.examples;

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

public class CreateArraylistObject {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		createListDemo_1();
		createListDemo_2();

	}
	//
	static void createListDemo_1()
	{
		List aList=new ArrayList();
		aList.add("a");
		aList.add("b");
		aList.add("c");
		System.out.println("Demo_1:"+aList);
	}
	//Create the asList using the methods in Arrays
	static void createListDemo_2()
	{
		List aList=Arrays.asList("1","2","3","6");
		System.out.println("Demo_2:"+aList);
		
	}
	
	

}

Output:

Demo_1:[a, b, c]
Demo_2:[1, 2, 3, 6]

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments