How do you create an empty list in Java?



A list is an ordered collection that holds a sequence of elements. In Java, a list is represented by the List Interface of the java.util package. This provides various methods to maintain and manipulate the list.

To create a list, you need to instantiate any of the implementing classes of this interface, suchas, ArrayList, LinkedList, Stack, Vector, etc. We can create a List of elements in multiple ways -

Let's explore these methods in detail.

Without specifying the "type"

We can create a List without specifying the type of elements it can hold. The compiler will throw a warning message for it.

List list = new ArrayList();

In this case, we can add any type of element to the list, but it is not recommended as it can lead to a ClassCastException at runtime.

Example

Below is an example of creating a List without specifying the type:

import java.util.List;
import java.util.ArrayList;
public class CreateListWithoutType {
   public static void main(String[] args) {
      // Create a List without specifying the type
      List list = new ArrayList();
      
      // Add elements of different types
      list.add("Hello");
      list.add(123);
      list.add(45.67);
      
      // Print the List
      System.out.println("List: " + list);
   }
}

Output

Following is the output of the above code:

List: [Hello, 123, 45.67]

Using ArrayList

We can create a List using the ArrayList class. This is the most commonly used way to create a List in Java.

List<T> list = new ArrayList<>();

Where T is the type of elements that the list can hold. For example, if we want to create a list of integers, we can do it as follows. In this case, we can only add elements of type Integer to the list.

List<Integer> list = new ArrayList<>();

Example

Below is an example of creating a List using the ArrayList class:

import java.util.List;
import java.util.ArrayList;
public class CreateListWithType {
   public static void main(String[] args) {
      // Create a List of Integer type
      List<Integer> list = new ArrayList<>();
      
      // Add elements to the List
      list.add(1);
      list.add(2);
      list.add(3);
      
      // Print the List
      System.out.println("List: " + list);
   }
}

Output

Following is the output of the above code:

List: [1, 2, 3]
Aishwarya Naglot
Aishwarya Naglot

Writing clean code… when the bugs aren’t looking.

Updated on: 2025-06-05T12:03:59+05:30

51K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements