java.util.ArrayList Initialization Example

In this post we will learn the different ways of initializing a java.util.ArrayList. Lets see the different ways of initialization.

1.Normal Way
2. Arrays.asList()
3. Anonymous Inner Class

Code Snippet

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

public class InitializingArrayListExample 
{
	public static void main(String args[])
	{
		//Normal Way
		List l1 = new ArrayList();
		l1.add("String 1");
		l1.add("String 2");
		l1.add("String 3");
		
		System.out.println("**Contents of l1**");
		System.out.println(l1);
		
		//Arrays.asList
		List l2 = new ArrayList(
				Arrays.asList("String 1","String 2","String 3"));
		
		System.out.println("**Contents of l2**");
		System.out.println(l2);
		
		//Anonymous inner class
		List l3 = new ArrayList(){
			{
				add("String 1");
				add("String 2");
				add("String 3");
			}};
			
		System.out.println("**Contents of l3**");
		System.out.println(l3);
	}
}

Output

**Contents of l1**
[String 1, String 2, String 3]
**Contents of l2**
[String 1, String 2, String 3]
**Contents of l3**
[String 1, String 2, String 3]

Leave a Reply

Your email address will not be published. Required fields are marked *