Java中的AbstractSequentialList的subList()方法用于获取此列表在指定的fromIndex(包括)和toIndex(不包括)之间的部分的视图。 (如果fromIndex和toIndex相等,则返回列表为空。)此列表支持返回的列表,因此返回列表中的非结构性更改会反映在此列表中,反之亦然。返回的列表支持此列表支持的所有可选列表操作。
用法:
protected List<E> subList(int fromIndex, int toIndex)
参数:这些方法采用两个参数:
- fromIndex:从中获取元素的起始索引。
- toIndex:要从中获取元素的结束索引。(不包括)
返回值:此方法返回此列表内指定范围的视图
异常:该方法抛出:
- IndexOutOfBoundsException:如果端点索引值超出范围。
- IllegalArgumentException:如果端点索引不正确。
下面的示例说明AbstractSequentialList.subList()方法:
例子1:
// Java program to demonstrate the
// working of subList() method
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// creating an AbstractSequentialList
AbstractSequentialList<Integer> arr
= new LinkedList<Integer>();
// use add() method
// to add values in the list
arr.add(1);
arr.add(2);
arr.add(3);
arr.add(12);
arr.add(9);
arr.add(13);
// prints the list before removing
System.out.println("AbstractSequentialList: "
+ arr);
// Getting subList of 1st 2 elements
// using subList() method
System.out.println("subList of 1st 2 elements: "
+ arr.subList(0, 2));
}
}
输出:
AbstractSequentialList: [1, 2, 3, 12, 9, 13] subList of 1st 2 elements: [1, 2]
示例2:
// Java program to demonstrate the
// working of subList() method
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// creating an AbstractSequentialList
AbstractSequentialList<Integer> arr
= new LinkedList<Integer>();
// use add() method
// to add values in the list
arr.add(1);
arr.add(2);
arr.add(3);
arr.add(12);
arr.add(9);
arr.add(13);
// prints the list before removing
System.out.println("AbstractSequentialList: "
+ arr);
System.out.println("Trying to get "
+ "subList of 11th elements: ");
try {
// Getting subList of 10th
// using subList() method
arr.subList(10, 11);
}
catch (Exception e) {
System.out.println(e);
}
}
}
输出:
AbstractSequentialList: [1, 2, 3, 12, 9, 13] Trying to get subList of 11th elements: java.lang.IndexOutOfBoundsException: toIndex = 11
相关用法
- Java AbstractSequentialList contains()用法及代码示例
- Java AbstractSequentialList hashCode()用法及代码示例
- Java AbstractSequentialList retainAll()用法及代码示例
- Java AbstractSequentialList toArray(T[])用法及代码示例
- Java AbstractSequentialList toArray()用法及代码示例
- Java AbstractSequentialList toString()用法及代码示例
- Java AbstractSequentialList size()用法及代码示例
- Java AbstractSequentialList conatinsAll()用法及代码示例
- Java AbstractSequentialList set(int, Object)用法及代码示例
- Java AbstractSequentialList isEmpty()用法及代码示例
- Java AbstractSequentialList equals()用法及代码示例
- Java AbstractSequentialList removeAll()用法及代码示例
- Java AbstractSequentialList clear()用法及代码示例
- Java AbstractSequentialList set()用法及代码示例
- Java AbstractSequentialList indexOf()用法及代码示例
注:本文由纯净天空筛选整理自Code_r大神的英文原创作品 AbstractSequentialList subList() method in Java with Example。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。