Java List remove() example

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

1. List remove() Method Overview

Definition:

The remove() method of the Java List interface is used to remove an element from the list. Depending on how it's invoked, it can either remove an element based on its index or based on the element itself.

Syntax:

list.remove(int index) 
list.remove(Object o)

Parameters:

1. int index - the index of the element to be removed.

2. Object o - the element itself to be removed from the list.

Key Points:

- The method can remove an element either based on its position or the element itself.

- It returns the removed element when using the index-based version and a boolean when using the object-based version.

- If the list does not contain the element, the object-based version returns false.

- Removing from an invalid index will throw an IndexOutOfBoundsException.

- The list will be automatically resized if an element is removed.

2. List remove() Method Example

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

public class ListRemoveExample {
    public static void main(String[] args) {
        // Create a new ArrayList with some elements
        List<String> colors = new ArrayList<>();
        colors.add("Red");
        colors.add("Green");
        colors.add("Blue");

        // Remove the element at index 1 (Green)
        String removedColor = colors.remove(1);
        System.out.println("Removed Color: " + removedColor);  // Outputs: Green
        System.out.println("Updated List: " + colors);        // Outputs: [Red, Blue]

        // Remove the element "Blue" from the list
        boolean isRemoved = colors.remove("Blue");
        System.out.println("Was Blue removed? " + isRemoved); // Outputs: true
        System.out.println("Final List: " + colors);          // Outputs: [Red]
    }
}

Output:

Removed Color: Green
Updated List: [Red, Blue]
Was Blue removed? true
Final List: [Red]

Explanation:

In the provided example:

1. We initiate an ArrayList with three colors.

2. First, we demonstrate the index-based remove() method by removing the color "Green" which is at index 1.

3. Then, we demonstrate the object-based remove() method by removing the color "Blue" directly.

The remove() method plays a crucial role in dynamic list operations, allowing the user to modify lists by removing elements based on either their positions or the elements themselves.

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