Table of contents
1.
Introduction
2.
Syntax
3.
Parameters
4.
Return Value
5.
Exceptions
6.
Examples
6.1.
Example 1: Creating a sublist from an ArrayList
6.2.
Example 2: Modifying the sublist
6.3.
Example 3: Modifying the original list
7.
Frequently Asked Questions
7.1.
Can a sublist be used independently of the original list?
7.2.
What happens if the original list is modified while using a sublist?
7.3.
Can sublists be created from other types of lists, such as LinkedList?
8.
Conclusion
Last Updated: Nov 9, 2024
Easy

Java ArrayList subList() Method

Author Rinki Deka
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Java's List is an interface which provides a way  for developers to work with collections of objects. It gives the ability to create sublists from existing lists, which allows it to handle and manipulate data more efficiently. Sometimes, you may need to extract a portion of a list, creating a new list containing only the selected elements. This is where the subList() method becomes useful. 

Java ArrayList subList() Method

In this article, we'll discuss how to use the subList() method in Java to create sublists from existing lists. We'll cover the syntax, parameters, return value, exceptions and examples to understand this in detail.

Syntax

The syntax for using the subList() method is:

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


The subList() method takes two parameters:

- fromIndex: The starting index of the sublist (inclusive)
 

- toIndex: The ending index of the sublist (exclusive)


It returns a new List object that contains the elements from the original list, starting from fromIndex & ending before toIndex.

Parameters

Now, look at the parameters used in the subList() method:

1. fromIndex:

   - This parameter specifies the starting index of the sublist.

   - It is an inclusive index, meaning the element at this index will be included in the sublist.

   - The value of fromIndex must be non-negative & less than or equal to the size of the original list.
 

2. toIndex:

   - This parameter specifies the ending index of the sublist.

   - It is an exclusive index, meaning the element at this index will not be included in the sublist.

   - The value of toIndex must be greater than or equal to fromIndex & less than or equal to the size of the original list.


Note: Always remember that the sublist is backed by the original list. Any modifications made to the sublist will affect the original list, & vice versa.

Return Value

The subList() method returns a new List object that represents a view of the specified range of the original list. The returned sublist is backed by the original list, which means that any changes made to the sublist will be reflected in the original list, and vice versa.

The type of the returned sublist is the same as the type of the original list. For example, if you call subList() on an ArrayList, the returned sublist will also be an ArrayList.

It's important to note that the returned sublist is not a new independent list. It is a view of the original list, sharing the same backing storage. This means that the sublist does not consume additional memory, as it references the same elements as the original list.

However, because the sublist is backed by the original list, modifying the original list while working with the sublist can lead to unexpected behavior and should be done with caution.

Exceptions

When using the subList() method, there are a few exceptions that we need to remember:

1. IndexOutOfBoundsException:

   - This exception is thrown if either fromIndex or toIndex is out of range.

   - If fromIndex is negative or greater than the size of the original list, an IndexOutOfBoundsException will be thrown.

   - If toIndex is less than fromIndex or greater than the size of the original list, an IndexOutOfBoundsException will be thrown.
 

2. IllegalArgumentException:

   - This exception is thrown if the endpoint indices are out of order (fromIndex > toIndex).

   - It indicates that the sublist range is invalid.
 

3. ConcurrentModificationException:

   - This exception is thrown if the original list is modified while the sublist is being used.

   - Since the sublist is backed by the original list, modifying the original list directly (not through the sublist) can cause inconsistencies and lead to this exception.
 

Note: To avoid these exceptions, make sure to provide valid index values within the range of the original list and be cautious when modifying the original list while working with sublists.

Examples

Let's look at some examples to see how the subList() method can be implemented in our codes: 

Example 1: Creating a sublist from an ArrayList

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

public class SublistExample {
    public static void main(String[] args) {
        // Creating the original list
        List<String> originalList = new ArrayList<>();
        originalList.add("apple");
        originalList.add("banana");
        originalList.add("cherry");
        originalList.add("date");
        originalList.add("elderberry");        
        // Creating a sublist from the original list (from index 1 to index 3, inclusive)
        List<String> sublist = originalList.subList(1, 4); // Index 4 is exclusive

        // Printing the sublist
        System.out.println("Sublist: " + sublist);
    }
}
You can also try this code with Online Java Compiler
Run Code


Output:

Sublist: [banana, cherry, date]


In this example, we create an ArrayList called `originalList` & add some elements to it. We then use the subList() method to create a sublist that includes elements from index 1 to index 3 (exclusive). The resulting sublist contains "banana", "cherry", & "date".

Example 2: Modifying the sublist

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

public class SublistExample {
    public static void main(String[] args) {
        // Creating the original list
        List<Integer> originalList = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
        
        // Creating a sublist from the original list (from index 1 to index 4)
        List<Integer> sublist = originalList.subList(1, 4);
        
        // Modifying the sublist
        sublist.set(1, 10); // Changes the second element of sublist (originally '3') to '10'

        // Printing the original list and the sublist
        System.out.println("Original List: " + originalList);
        System.out.println("Sublist: " + sublist);
    }
}
You can also try this code with Online Java Compiler
Run Code


Output:

Original List: [1, 2, 10, 4, 5]
Sublist: [2, 10, 4]


In this example, we create an ArrayList called `originalList` with some integer elements. We create a sublist using the subList() method. We then modify an element in the sublist using the set() method. As you can see, the modification is reflected in both the sublist & the original list.

Example 3: Modifying the original list

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

public class SublistExample {
    public static void main(String[] args) {
        // Creating the original list
        List<String> originalList = new ArrayList<>(Arrays.asList("a", "b", "c", "d", "e"));       
        // Creating a sublist from the original list (from index 1 to index 4)
        List<String> sublist = originalList.subList(1, 4);
        
        // Modifying the original list
        originalList.set(2, "x");

        // Printing the original list and the sublist
        System.out.println("Original List: " + originalList);
        System.out.println("Sublist: " + sublist);
    }
}
You can also try this code with Online Java Compiler
Run Code


Output:

Original List: [a, b, x, d, e]
Sublist: [b, x, d]


In this example, we create an ArrayList called `originalList` with some string elements. We create a sublist using the subList() method. We then modify an element in the original list using the set() method. As you can see, the modification is reflected in both the original list & the sublist.

Frequently Asked Questions

Can a sublist be used independently of the original list?

No, a sublist is a view of the original list & is backed by it. Changes made to the sublist affect the original list & vice versa.

What happens if the original list is modified while using a sublist?

Modifying the original list while using a sublist can lead to a ConcurrentModificationException, as the sublist becomes inconsistent with the original list.

Can sublists be created from other types of lists, such as LinkedList?

Yes, the subList() method is defined in the List interface, so it can be used with any implementation of List, including ArrayList, LinkedList, & others.

Conclusion

In this article, we discussed the subList() method in Java, which allows us to create sublists from existing lists. We covered the syntax, parameters, return value, exceptions, & examples of using subList(). How to create and work with sublists is very important when you need to extract or manipulate portions of a list efficiently. Always remember to handle exceptions properly and be cautious when modifying the original list while using sublists.

You can also check out our other blogs on Code360.

Live masterclass