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 thetoIndex
.
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:
2.1 Reason for Failure
- Case 1: fromIndex < 0: The
fromIndex
parameter is less than 0.subList(int fromIndex, int toIndex)
requiresfromIndex
to be non-negative. Negative indices are invalid, thus anIndexOutOfBoundsException
is thrown. - Case 2: toIndex > size: The
toIndex
parameter exceeds the size of the list.subList(int fromIndex, int toIndex)
requirestoIndex
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 validtoIndex
is 5. SincetoIndex
is 6, anIndexOutOfBoundsException
is thrown. - Case 3: fromIndex > toIndex: The
fromIndex
parameter is greater than thetoIndex
parameter.subList(int fromIndex, int toIndex)
requiresfromIndex
to be less than or equal totoIndex
. SincefromIndex
is 4 andtoIndex
is 2, anIllegalArgumentException
(a subtype ofIndexOutOfBoundsException
) 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 totoIndex
.
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
.
You can download the full source code of this example here: Java List sublist indexoutofboundsexception