Posted in

防止 Java 中 List.subList() 引发 IndexOutOfBoundsException_AI阅读总结 — 包阅AI

包阅导读总结

1.

关键词:Java、List.subList()、IndexOutOfBoundsException、避免异常、正确使用

2.

总结:

本文探讨了 Java 中 List.subList()方法,指出不当使用会导致 IndexOutOfBoundsException,介绍了其工作原理、异常产生原因及避免方法,通过示例和代码演示了正确与错误的用法。

3.

主要内容:

– 概述

– List.subList()可创建列表部分视图,由起始和结束索引定义。

– 返回的子列表由原列表支持,修改会相互影响。

– 异常原因

– fromIndex 小于 0。

– toIndex 大于列表大小。

– fromIndex 大于 toIndex。

– 异常示例

– 展示了三种导致异常的场景及相应代码和输出。

– 避免异常

– 确保 fromIndex 大于等于 0。

– 确保 toIndex 小于等于列表大小。

– 确保 fromIndex 小于等于 toIndex。

– 结论

– 强调正确使用索引以避免异常。

思维导图:

文章地址:https://www.javacodegeeks.com/preventing-indexoutofboundsexception-with-list-sublist-in-java.html

文章来源:javacodegeeks.com

作者:Omozegie Aziegbe

发布时间:2024/6/20 13:00

语言:英文

总字数:621字

预计阅读时间:3分钟

评分:84分

标签:IndexOutOfBoundsException,Java 异常,List.subList


以下为原文内容

本内容来源于用户推荐转载,旨在分享知识与观点,如有侵权请联系删除 联系邮箱 media@ilingban.com

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.