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
fromIndexis less than 0. - The
toIndexis greater than the size of the list. - The
fromIndexis 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
fromIndexparameter is less than 0.subList(int fromIndex, int toIndex)requiresfromIndexto be non-negative. Negative indices are invalid, thus anIndexOutOfBoundsExceptionis thrown. - Case 2: toIndex > size: The
toIndexparameter exceeds the size of the list.subList(int fromIndex, int toIndex)requirestoIndexto be less than or equal to the size of the list. In this example, the list has a size of 5, so the maximum validtoIndexis 5. SincetoIndexis 6, anIndexOutOfBoundsExceptionis thrown. - Case 3: fromIndex > toIndex: The
fromIndexparameter is greater than thetoIndexparameter.subList(int fromIndex, int toIndex)requiresfromIndexto be less than or equal totoIndex. SincefromIndexis 4 andtoIndexis 2, anIllegalArgumentException(a subtype ofIndexOutOfBoundsException) is thrown.
3. Avoiding the Exception
To avoid IndexOutOfBoundsException, always ensure that:
fromIndexis greater than or equal to 0.toIndexis less than or equal to the size of the list.fromIndexis 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


