Yandex

Java Advanced ConceptsJava Advanced Concepts3

Java ArrayList removeRange() method
Syntax and Examples


Introduction

Sometimes you need to remove a chunk of elements from an ArrayList, not just one at a time. The `removeRange()` method allows you to do exactly that – efficiently removing a specified range of elements from the list. This is particularly useful when dealing with scenarios where you're filtering or modifying a portion of your data.

Syntax

public void removeRange(int fromIndex, int toIndex)

Parameters

Parameter Description
fromIndex The index of the first element to be removed (inclusive).
toIndex The index *after* the last element to be removed (exclusive). In other words, elements from fromIndex up to (but not including) toIndex are removed.

Return Value

This method returns void; it doesn't return any value. The changes happen directly within the original ArrayList.

Examples

Example 1: Removing a Segment of Numbers

Let’s start with a simple example where we remove elements from an ArrayList containing numbers.

import java.util.ArrayList;

public class RemoveRangeExample {
    public static void main(String[] args) {
        ArrayList numbers = new ArrayList<>();
        numbers.add(10);
        numbers.add(20);
        numbers.add(30);
        numbers.add(40);
        numbers.add(50);
        numbers.add(60);
        numbers.add(70);

        System.out.println("Original list: " + numbers);

        // Remove elements from index 2 (inclusive) to index 5 (exclusive)
        numbers.removeRange(2, 5);  // Removes 30, 40, and 50

        System.out.println("List after removeRange(): " + numbers);
    }
}
Original list: [10, 20, 30, 40, 50, 60, 70]
List after removeRange(): [10, 20, 60, 70]

In this example, we created an ArrayList named numbers and initialized it with some integer values. Then, we called removeRange(2, 5), which removes elements at indices 2, 3, and 4 (inclusive). Notice that the element at index 5 is *not* removed because the second parameter is exclusive.

Example 2: Removing Elements from the Beginning

This example shows how to remove elements starting from the beginning of the list. This is useful if you want to clear a portion or all of the list's initial contents.

import java.util.ArrayList;

public class RemoveRangeFromBeginning {
    public static void main(String[] args) {
        ArrayList names = new ArrayList<>();
        names.add("Alice");
        names.add("Bob");
        names.add("Charlie");
        names.add("Ram");
        names.add("Eve");

        System.out.println("Original list: " + names);

        // Remove elements from index 0 (inclusive) to index 3 (exclusive)
        names.removeRange(0, 3);  // Removes Alice, Bob, and Charlie

        System.out.println("List after removeRange(): " + names);
    }
}
Original list: [Alice, Bob, Charlie, Ram, Eve]
List after removeRange(): [Ram, Eve]

Here, we're removing the first three elements of the names list. This is equivalent to clearing out the beginning portion of the list.

Example 3: Removing All Elements

To remove all elements from an ArrayList using removeRange(), you can specify a range that covers the entire list.

import java.util.ArrayList;

public class RemoveAllElements {
    public static void main(String[] args) {
        ArrayList letters = new ArrayList<>();
        letters.add('A');
        letters.add('B');
        letters.add('C');
        letters.add('D');

        System.out.println("Original list: " + letters);

        // Remove all elements by specifying a range from 0 to the size of the list
        letters.removeRange(0, letters.size());

        System.out.println("List after removeRange(): " + letters);
    }
}
Original list: [A, B, C, D]
List after removeRange(): []

In this example, we are removing all elements of the `letters` list. The toIndex parameter is set to letters.size() which means it will remove from index 0 up to but not including the last element.

Important Considerations

  • Index OutOfBoundsException: If either fromIndex or toIndex is out of bounds, an IndexOutOfBoundsException will be thrown.
  • Invalid Range: If fromIndex > toIndex, the method does nothing and no elements are removed.
  • Shifting Elements: Removing a range of elements requires shifting subsequent elements to fill the gap. This can be relatively expensive in terms of performance if you're removing large chunks from the middle of the list.

Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M