Yandex

Java Advanced ConceptsJava Advanced Concepts3

Java ArrayList subList() method
Syntax and Examples


Introduction

Sometimes you need to work with a portion of an ArrayList instead of the entire list. The subList() method provides exactly that functionality. It allows you to create a view of a section of the original ArrayList without creating a new copy of the data itself, making it memory-efficient.

Syntax

    
    public List<E> subList(int fromIndex,
                              int toIndex)
    
  

Parameters

Parameter Description
fromIndex The index of the first element included in the sublist (inclusive).
toIndex The index of the last element *excluded* from the sublist. It's one past the last element to be included.

Return Value

The subList() method returns a List<E> object, which is a view of the portion of the original ArrayList.

Important Considerations

  • The returned sublist is linked to the original list. Modifications to the sublist will affect the original list and vice-versa.
  • The indices used in subList() must be within the bounds of the original list (0 <= fromIndex <= toIndex <= size()). Otherwise, an IndexOutOfBoundsException is thrown.
  • The sublist doesn’t create a new ArrayList; it's essentially a view into the original one.

Examples

Example 1: Basic Sublist Creation

This example demonstrates creating a basic sublist from an existing ArrayList.

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

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

            // Create a sublist from index 1 (inclusive) to index 3 (exclusive)
            List<String> subNames = names.subList(1, 3);

            // Print the original list and sublist
            System.out.println("Original List: " + names);
            System.out.println("Sublist: " + subNames);
        }
    }
  

    Original List: [Alice, Bob, Charlie, Ram, Eve]
    Sublist: [Bob, Charlie]

In this example, subList(1, 3) creates a view of the list containing elements at indices 1 and 2 (i.e., "Bob" and "Charlie"). Notice that index 3 is *not* included.

Example 2: Modifying the Sublist

This example shows how changes to the sublist affect the original list, and vice versa.

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

    public class SubListExample2 {
        public static void main(String[] args) {
            // Create an ArrayList
            List<Integer> numbers = new ArrayList<>();
            numbers.add(10);
            numbers.add(20);
            numbers.add(30);
            numbers.add(40);

            // Create a sublist from index 1 to index 3
            List<Integer> subNumbers = numbers.subList(1, 3);

            // Modify the sublist
            subNumbers.set(0, 25); // Changes the element at index 1 in the sublist
            subNumbers.add(35);  // Adds an element to the end of the sublist

            // Print both lists
            System.out.println("Original List: " + numbers);
            System.out.println("Sublist: " + subNumbers);
        }
    }
  

    Original List: [10, 25, 30, 40, 35]
    Sublist: [25, 30, 35]

When we modified the sublist (changed element at index 1 to 25 and added 35), these changes were also reflected in the original list. This demonstrates that a sublist is linked to its parent ArrayList.

Example 3: Handling IndexOutOfBoundsException

This example illustrates what happens when you provide invalid indices to subList().

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

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

            try {
                // Attempt to create a sublist with invalid indices
                List<String> invalidSublist = colors.subList(0, 5); // IndexOutOfBoundsException will be thrown

                System.out.println("Sublist: " + invalidSublist);
            } catch (IndexOutOfBoundsException e) {
                System.out.println("Caught an exception: " + e.getMessage());
            }
        }
    }
  

    Caught an exception: toIndex = 5 greater than size = 3

Because we attempted to create a sublist with `toIndex` (5) exceeding the list's size (3), an IndexOutOfBoundsException was thrown. Always ensure your indices are valid.


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