ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
# 如何获取`ArrayList`的子列表 > 原文: [https://beginnersbook.com/2013/12/how-to-get-sublist-of-an-arraylist-with-example/](https://beginnersbook.com/2013/12/how-to-get-sublist-of-an-arraylist-with-example/) 在本教程中,我们将了解如何从现有`ArrayList`获取子列表。我们将使用`ArrayList`类的[`subList`](https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#subList(int, int))方法来完成它。 `List subList(int fromIndex, int toIndex)` 这里`fromIndex`是包容性的,`toIndex`是独占的。关于这种方法,我在本文末尾分享了一些重要的观点。 ## 从`ArrayList`获取子列表的示例 以下示例中的注意事项: `subList`方法返回一个列表,因此将子列表存储在另一个`ArrayList`中,我们必须以与下面示例中相同的方式对返回值进行类型转换。另一方面,如果我们将返回的子列表存储到列表中,则无需键入转换(请参阅示例)。 ```java package beginnersbook.com; import java.util.ArrayList; import java.util.List; public class SublistExample { public static void main(String a[]){ ArrayList<String> al = new ArrayList<String>(); //Addition of elements in ArrayList al.add("Steve"); al.add("Justin"); al.add("Ajeet"); al.add("John"); al.add("Arnold"); al.add("Chaitanya"); System.out.println("Original ArrayList Content: "+al); //Sublist to ArrayList ArrayList<String> al2 = new ArrayList<String>(al.subList(1, 4)); System.out.println("SubList stored in ArrayList: "+al2); //Sublist to List List<String> list = al.subList(1, 4); System.out.println("SubList stored in List: "+list); } } ``` 输出: ```java Original ArrayList Content: [Steve, Justin, Ajeet, John, Arnold, Chaitanya] SubList stored in ArrayList: [Justin, Ajeet, John] SubList stored in List: [Justin, Ajeet, John] ``` **注意:** 如果指定的索引超出了`ArrayList`的范围(`fromIndex > 0 || toIndex < size`),则`subList`方法抛出[`IndexOutOfBoundsException`](https://docs.oracle.com/javase/7/docs/api/java/lang/IndexOutOfBoundsException.html)。 [`IllegalArgumentException`](https://docs.oracle.com/javase/7/docs/api/java/lang/IllegalArgumentException.htm) - 如果起始索引大于终点索引(`fromIndex < toIndex`)。