Java List add() example

In this guide, you will learn about the List add() method in Java programming and how to use it with an example.

1. List add() Method Overview

Definition:

The add() method of the Java List interface is used to append an element to the end of a list or insert it at a specific position.

Syntax:

list.add(E e)

- This appends the specified element to the end of the list.

list.add(int index, E element)

- This inserts the specified element at the specified position in the list.

Parameters:

1. E e - The element to be appended to the list.

2. int index - The index at which the specified element is to be inserted.

3. E element - The element to be inserted.

Key Points:

- If the list is immutable like that returned by List.of(), the add() method will throw an UnsupportedOperationException.

- The add() method may throw other runtime exceptions, such as ClassCastException, IllegalArgumentException, or IndexOutOfBoundsException, depending on the circumstances.

- The second syntax allows for positional insertions, but you must be cautious of the index bounds.

2. List add() Method Example

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

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

        // Use add(E e) to append elements to the list
        fruits.add("Apple");
        fruits.add("Banana");
        System.out.println(fruits);  // Outputs: [Apple, Banana]

        // Use add(int index, E element) to insert an element at a specific position
        fruits.add(1, "Cherry");
        System.out.println(fruits);  // Outputs: [Apple, Cherry, Banana]

        // Trying to add at an out-of-bounds index will throw an exception
        // Uncommenting the following line will throw java.lang.IndexOutOfBoundsException
        // fruits.add(5, "Orange");
    }
}

Output:

[Apple, Banana]
[Apple, Cherry, Banana]

Explanation:

In the provided example:

1. We initiated an ArrayList of strings representing fruits.

2. We added "Apple" and "Banana" to the end of the list using the first variant of the add() method.

3. Later, we inserted "Cherry" at the second position in the list, pushing "Banana" to the third position.

4. The commented-out line demonstrates a potential pitfall: trying to add an element at an out-of-bounds index. If uncommented, this line would throw an IndexOutOfBoundsException.

The add() method is fundamental in list operations, allowing for dynamic resizing and positional element insertions.

Related Java List methods

Java List add() example
Java List clear() example
Java List contains() example
Java List get() example
Java List indexOf() example
Java List remove() example
Java List size() example
Java List toArray() example

Comments