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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。