In this tutorial, we will see 2 ways to create ArrayList in Java.

Create ArrayList in Java :

Java Provides 2 different ways to create an ArrayList,

Method 1 :

Creating ArrayList using Arrays class, Arrays.asList();

Syntax :

ArrayList list = new ArrayList(Arrays.asList(Object obj1, Object obj2, Object obj3, ..,objn));

Example :

[java]
import java.util.ArrayList;
import java.util.Arrays;

public class Method1 {
public static void main(String args[]) {
ArrayList<String> fruits = new ArrayList<String>(
Arrays.asList("Apple", "Banana", "Grapes","Mango"));
System.out.println("List of all Fruits – "+fruits);
}
}
[/java]

Output :

List of all Fruits - [Apple, Banana, Grapes, Mango]

Method 2 :

Creating ArrayList using java.util.ArrayList class constructor.

Syntax :

ArrayList fruitsList = new ArrayList();
        fruitsList.add("Banana");
        fruitsList.add("Apple");
        fruitsList.add("Grapes");
        fruitsList.add("Mango");

Example :

[java]
import java.util.ArrayList;
import java.util.Arrays;

public class Sample {
public static void main(String args[]) {
ArrayList fruitsList = new ArrayList();
fruitsList.add("Banana");
fruitsList.add("Apple");
fruitsList.add("Grapes");
fruitsList.add("Mango");
System.out.println("List of all Fruits – "+fruitsList);
}
}
[/java]

Output :

List of all Fruits - [Banana, Apple, Grapes, Mango]

Reference :

How Arrays Works in Java

How ArrayList works in Java

Happy Learning 🙂

About the Author:

Founder of onlinetutorialspoint.com Love Java, Python, Shell and opensource frameworks. Follow him on twitter and facebook for latest updates.

Leave A Comment