How To Create A List In Java

7 min read

Learning how to create a list in Java is essential because a list stores an ordered collection of values that can be accessed, updated, searched, and processed efficiently. Java provides several ways to create lists, including ArrayList, LinkedList, List.of(), and Arrays.asList(). The best option depends on whether the collection must be mutable, how it will be accessed, and which Java version is being used.

What Is a List in Java?

A list is an ordered collection that can contain multiple elements. That's why each element has an index, and indexing starts at 0. To give you an idea, the first element is at index 0, the second is at index 1, and so on.

Java lists belong to the java.And list interface. Now, util. This interface defines common list operations, while classes such as ArrayList and LinkedList provide concrete implementations.

Common list capabilities include:

  • Adding elements
  • Accessing elements by index
  • Updating existing elements
  • Removing elements
  • Checking whether a value exists
  • Finding an element’s position
  • Sorting and iterating through values

A list can contain objects of almost any type, such as strings, numbers, custom objects, or other collections.

Importing the Required Classes

Before using a list, import the appropriate classes from the java.util package:

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

If a linked implementation is needed, import LinkedList as well:

import java.util.LinkedList;

The wildcard import below also makes all java.util classes available, although explicit imports are usually clearer:

import java.util.*;

Creating a Mutable List with ArrayList

The most common way to create a list in Java is with ArrayList. It provides a resizable array that grows automatically when more elements are added.

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

public class Main {
    public static void main(String[] args) {
        List fruits = new ArrayList<>();

        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");

        System.out.println(fruits);
    }
}

Output:

[Apple, Banana, Cherry]

The declaration uses generics to specify that the list may contain only strings:

List fruits

Using generics prevents incompatible values from being added and removes the need for manual type casting when retrieving elements.

The new ArrayList<>() expression creates the actual mutable list. On the flip side, the empty angle brackets are called the diamond operator. They allow Java to infer the element type from the left side of the assignment Worth knowing..

Creating a List with Initial Values

An empty ArrayList can be populated using repeated calls to add():

List scores = new ArrayList<>();
scores.add(90);
scores.add(85);
scores.add(98);

A more compact approach is to create an array-backed list and copy it into an ArrayList:

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

List colors = new ArrayList<>(
        Arrays.asList("Red", "Green", "Blue")
);

colors.add("Yellow");

This creates a mutable list. Worth adding: values can be added or removed because the final object is an ArrayList, not the fixed-size result returned directly by Arrays. asList().

Since Java 9, List.of() provides a concise way to create a list from known values:

List colors = List.of("Red", "Green", "Blue");

Still, a list created by List.of() is immutable. Its contents cannot be changed after creation:

colors.add("Yellow"); // Throws UnsupportedOperationException

Use List.of() for values that should remain constant. Use an ArrayList when the collection must grow or change Easy to understand, harder to ignore..

Creating a List with LinkedList

A LinkedList is another standard implementation of the List interface:

import java.util.LinkedList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List tasks = new LinkedList<>();

        tasks.add("Write report");
        tasks.add("Review email");
        tasks.add("Attend meeting");

        System.out.println(tasks);
    }
}

A linked list stores elements as connected nodes. It can be useful when an application frequently inserts or removes elements near the beginning or middle of a collection It's one of those things that adds up..

For ordinary indexed access and appending operations, ArrayList is generally faster because it stores elements in contiguous array positions and benefits from better cache locality.

Using var to Create a List

Java 10 introduced local-variable type inference through the var keyword:

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

var students = new ArrayList();
students.add("Maya");
students.add("Noah");

This is valid only for local variables. The inferred type is ArrayList<String>, not List<String>. If code should depend on the interface rather than a specific implementation, an explicit declaration is clearer:

List students = new

`ArrayList<>();`

This preserves the flexibility to swap implementations later without changing the rest of the code.

## Accessing and Modifying Elements

Lists support indexed access, allowing precise control over individual elements.

```java
List colors = new ArrayList<>(List.of("Red", "Green", "Blue"));

// Read an element (zero-based index)
String first = colors.get(0); // "Red"

// Replace an element
colors.set(1, "Yellow"); // List becomes ["Red", "Yellow", "Blue"]

// Insert at a specific position (shifts subsequent elements right)
colors.add(1, "Orange"); // List becomes ["Red", "Orange", "Yellow", "Blue"]

// Remove by index
String removed = colors.remove(2); // Removes "Yellow", returns it

// Remove by object (removes first occurrence)
colors.remove("Red");

Attempting an invalid index (negative or >= size()) throws IndexOutOfBoundsException Worth knowing..

Iterating Over a List

Enhanced For Loop (For-Each)

Best for read-only traversal when the index is not needed The details matter here..

for (String color : colors) {
    System.out.println(color);
}

Traditional For Loop

Required when the index is needed or when modifying the list structure (e.g., removing elements during iteration).

for (int i = 0; i < colors.size(); i++) {
    System.out.println(i + ": " + colors.get(i));
}

Iterator / ListIterator

ListIterator allows bidirectional traversal and safe modification during iteration It's one of those things that adds up..

import java.util.ListIterator;

ListIterator it = colors.next();
    if (c.Which means equals("Orange")) {
        it. Here's the thing — hasNext()) {
    String c = it. listIterator();
while (it.set("Amber");      // Replace current element
        it.

### Streams (Java 8+)
Functional-style processing, ideal for filtering, mapping, or collecting results.

```java
colors.stream()
      .filter(c -> c.length() > 4)
      .map(String::toUpperCase)
      .forEach(System.out::println);

Common Utility Operations

The Collections class provides static algorithms that operate on List instances Took long enough..

import java.util.Collections;
import java.util.Comparator;

List numbers = new ArrayList<>(List.of(5, 2, 8, 1, 9));

Collections.sort(numbers);                 // Natural order: [1, 2, 5, 8, 9]
Collections.Think about it: shuffle(numbers);              // Random permutation
Collections. reverse(numbers);              // Reverse current order
Collections.swap(numbers, 0, numbers.

int index = Collections.binarySearch(numbers, 5); // Requires sorted list
int max = Collections.max(numbers);
int min = Collections.

For custom sorting, pass a `Comparator`:

```java
List words = new ArrayList<>(List.of("apple", "fig", "banana"));
words.sort(Comparator.comparingInt(String::length)); // Sort by length
// Result: [fig, apple, banana]

Checking Contents and Size

boolean hasBlue = colors.contains("Blue");      // true
boolean empty   = colors.isEmpty();             // false
int count       = colors.size();                // Number of elements
int idx         = colors.indexOf("Yellow");     // First index, or -1
int lastIdx     = colors.lastIndexOf("Yellow"); // Last index, or -1

Converting Between Lists and Arrays

List to Array

String[] array = colors.toArray(new String[0]); // Preferred: type-safe, sized correctly

Array to List

String[] arr = {"A", "B", "C"};
List list = new ArrayList<>(Arrays.asList(arr)); // Mutable copy
// Or (Java 10+):
var list = Arrays.asList(arr); // Fixed-size list backed by array

Performance Characteristics at a Glance

Operation ArrayList LinkedList
get(index) / set(index, e) O(1) (Fast) O(n) (Slow)
add(e) (Append) O(1) Amortized O(1)
add(index, e) / remove(index) O(n) (Shift required) O(n) (Traversal required)
remove(Object) O(n) O(n)
Memory Overhead Low (Object array) High (Node objects)
Cache Locality Excellent Poor

Rule of thumb: Default to ArrayList. Switch to LinkedList only if profiling proves that frequent insertions/removals at the head or middle are a genuine bottleneck and the list is large enough for the overhead to matter.

Conclusion

Let's talk about the Java List interface provides a versatile, ordered collection with precise

control over algorithmic behavior and resource allocation. In most scenarios, defaulting to ArrayList offers the best balance of simplicity and performance; reserve LinkedList for rare cases involving heavy internal reshuffling. Leveraging the Collections suite alongside the core List API enables developers to handle everything from basic filtering and sorting to complex structural modifications without reinventing the wheel. Plus, as demonstrated above, the decision between ArrayList and LinkedList hinges primarily on whether you value fast indexed access or frequent insertions/deletions at the front of the sequence. With this comprehensive toolkit, you are well-equipped to implement dependable, scalable solutions using the standard Java collections framework.

More to Read

Out This Morning

Similar Territory

If This Caught Your Eye

Thank you for reading about How To Create A List In Java. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home