javacodex.com
Java Examples
Java Examples
memu home questions

Initialize An ArrayList

There are many ways to to initialize an ArrayList. Here are a few examples.

Source: (InitializeArrayList.java)

import java.util.*;
 
public class InitializeArrayList {
 
   public static void main(String[] args) {
 
      // Normal way
      List<String> list1 = new ArrayList<String>();
      list1.add("George");
      list1.add("Paul");
      list1.add("John");
      list1.add("Ringo");
      System.out.println("list1: " + list1);
 
 
      // One liner
      List<String> list2 =  new ArrayList<String>(
         Arrays.asList("Gilligan", "Skipper", "Ginger", "Mary Ann", "Professor"));  
      System.out.println("list2: " + list2);
 
 
      // Another One liner
      List<String> list3 = Arrays.asList("One", "Two", "Three", "Four");
      System.out.println("list3: " + list3);
 
 
      //Anonymous inner class
      List<String> list4 = new ArrayList<String>() {{
         add("AAAA");
         add("BBBB");
         add("CCCC");
         add("DDDD");
      }};
      System.out.println("list4: " + list4);
 
   }
}
 

Output:

$ java InitializeArrayList 
list1: [George, Paul, John, Ringo]
list2: [Gilligan, Skipper, Ginger, Mary Ann, Professor]
list3: [One, Two, Three, Four]
list4: [AAAA, BBBB, CCCC, DDDD]

Contact: javacodex@yahoo.com