2 ways on How to Initialize an Arraylist in java with Example

I have already discussed how to sort ArrayList and how to find length of an ArrayList in java.In this post we will see how to initialize an ArrayList in java with example.

Read Also :  How to Reverse an ArrayList in java

 Method 1: Using Arrays.asList() method

Syntax :

ArrayList<Type> obj = new ArrayList<Type>(
        Arrays.asList(Object o1, Object o2, Object o3, ....so on));

Example:



import java.util.*;

 public class Initialization1 {
    public static void main(String args[]) {
       ArrayList<String> obj = new ArrayList<String>(
    Arrays.asList("Boston", "Chicago", "Dallas"));
       System.out.println("Elements are:"+obj);
  }
}




Output
Elements are:[Boston, Chicago, Dallas]
Method 2: Normal Initialization method

Syntax :


ArrayList<T> obj = new ArrayList<T>();
    obj.add("Object o1");
    obj.add("Object o2");
    obj.add("Object o3");
                        ...
                        ...


Example:



import java.util.*;

 public class Initialization2 {
    public static void main(String args[]) {
       ArrayList<String> cars = new ArrayList<String>();
    cars.add("Honda");
    cars.add("Hyundai");
    cars.add("Toyota");
    System.out.println("Cars stored in array list are: "+ cars);
  }
}


Output

Cars stored in array list are: [Honda, Hyundai, Toyota]




About The Author

Subham Mittal has worked in Oracle for 3 years .
For more java articles ,Click here to Subscribe JavaHungry