Core Java

Preventing IndexOutOfBoundsException with List.subList() in Java

The List.subList() method in Java allows you to create a view of a portion of a list, defined by a starting and ending index. However, improper use of this method can lead to IndexOutOfBoundsException. This article will explore how subList() works and how to avoid this exception through proper usage.

1. Overview of List.subList()

The subList(int fromIndex, int toIndex) method returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive. The returned list is backed by the original list, meaning that changes to the sublist will be reflected in the original list, and vice-versa.

1.1 Common Causes of IndexOutOfBoundsException

The IndexOutOfBoundsException occurs when:

  • The fromIndex is less than 0.
  • The toIndex is greater than the size of the list.
  • The fromIndex is greater than the toIndex.

2. Demonstrating the Exception with Examples

Here’s an example demonstrating various scenarios that can lead to IndexOutOfBoundsException:

SubListExample.java

public class SubListExample {

    public static void main(String[] args) {
        List<String> originalList = new ArrayList<>(Arrays.asList("A", "B", "C", "D", "E"));

        // Case 1: fromIndex < 0
        List<String< sublist = originalList.subList(-1, 3);
        System.out.println(sublist);

        // Case 2: toIndex > size
        List<String> sublist2 = originalList.subList(2, 6);
        System.out.println(sublist2);

        // Case 3: fromIndex > toIndex
        List<String> sublist3 = originalList.subList(4, 2);
        System.out.println(sublist3);

    }
}

The code above (Case 1) produces the following output:

Fig 1: Example output demonstrating a subList IndexOutOfBoundsException
Fig 1: Example output demonstrating a subList IndexOutOfBoundsException

2.1 Reason for Failure

  • Case 1: fromIndex < 0: The fromIndex parameter is less than 0. subList(int fromIndex, int toIndex) requires fromIndex to be non-negative. Negative indices are invalid, thus an IndexOutOfBoundsException is thrown.
  • Case 2: toIndex > size: The toIndex parameter exceeds the size of the list. subList(int fromIndex, int toIndex) requires toIndex to be less than or equal to the size of the list. In this example, the list has a size of 5, so the maximum valid toIndex is 5. Since toIndex is 6, an IndexOutOfBoundsException is thrown.
  • Case 3: fromIndex > toIndex: The fromIndex parameter is greater than the toIndex parameter. subList(int fromIndex, int toIndex) requires fromIndex to be less than or equal to toIndex. Since fromIndex is 4 and toIndex is 2, an IllegalArgumentException (a subtype of IndexOutOfBoundsException) is thrown.

3. Avoiding the Exception

To avoid IndexOutOfBoundsException, always ensure that:

  • fromIndex is greater than or equal to 0.
  • toIndex is less than or equal to the size of the list.
  • fromIndex is less than or equal to toIndex.

Here is how we can safely use subList():

SafeSubListExample.java

public class SafeSubListExample {

    public static void main(String[] args) {

        List<String> originalList = new ArrayList<>(Arrays.asList("A", "B", "C", "D", "E"));
        int fromIndex = 1;
        int toIndex = 4;

        if (fromIndex >= 0 && toIndex <= originalList.size() && fromIndex <= toIndex) {
            List<String> sublist = originalList.subList(fromIndex, toIndex);
            System.out.println("Sublist: " + sublist);
        }
    }
}

The provided code snippet above demonstrates the safe and correct usage of the subList() method to avoid IndexOutOfBoundsException by validating the indices before calling the method. By checking that fromIndex is non-negative, toIndex does not exceed the list size, and fromIndex is less than or equal to toIndex, the code safely creates a sublist of the original list.

4. Conclusion

In this article, we explored how to effectively use the subList() method in Java lists while avoiding the common IndexOutOfBoundsException. We discussed how subList() works, provided examples of scenarios that cause the exception. By understanding the constraints and correctly using indices, we can utilize the power of subList() without encountering errors. In conclusion, ensuring that indices are within valid bounds is key to preventing IndexOutOfBoundsException.

5. Download the Source Code

This article covers Java’s List.subList() method and how to prevent IndexOutOfBoundsException.

Download
You can download the full source code of this example here: Java List sublist indexoutofboundsexception

Omozegie Aziegbe

Omos Aziegbe is a technical writer and web/application developer with a BSc in Computer Science and Software Engineering from the University of Bedfordshire. Specializing in Java enterprise applications with the Jakarta EE framework, Omos also works with HTML5, CSS, and JavaScript for web development. As a freelance web developer, Omos combines technical expertise with research and writing on topics such as software engineering, programming, web application development, computer science, and technology.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button