2021-05-22
List 接口定義:
public interface List<E> extends Collection<E>
雖然 List 是 Collection 接口的子接口,但是 List 接口本身會提供有許多新的處理方法,這些方法是擴展來的例隆,有如下幾個重要的擴展方法:
方法 | 描述 |
---|---|
void add(int index, E element) | 在指定索引位置處添加元素 |
E get(int index) |
根據(jù)索引獲取保存的數(shù)據(jù) |
int indexOf(Object o) | 獲取指定數(shù)據(jù)的索引位置 |
ListIterator<E> listIterator() | 獲取 ListIterator 接口對象實例 |
E set(int index, E element) | 修改指定索引位置的數(shù)據(jù) |
default void sort(Comparator<? super E> c) | 使用特定比較器實現(xiàn)排序操作 |
List<E> subList(int fromIndex, int toIndex) | 截取子集合 |
@SafeVarargs static <E> List<E> of(E... elements) | [Since 9] 通過給定元素創(chuàng)建 List 集合 |
使用 of() 方法實現(xiàn) List 集合創(chuàng)建
public class ListDemo {
public static void main(String[] args) {
// 此時所創(chuàng)建的 List 集合內(nèi)部存在重復的數(shù)據(jù)內(nèi)容
List all = List.of("Jade", "Bamboo", "Lemon", "Jade");
System.out.println(all);
for (Object obj : all.toArray()) {
System.out.println(obj);
}
}
}
以上的 List 集合從嚴格意義上來講是屬于一種半成品的工具類阔逼,如果此時執(zhí)行的一下的程序代碼,則會拋出異常:
List all = List.of("Jade", "Bamboo", "Lemon", "Jade");
all.add("wust"); // Exception in thread "main" java.lang.UnsupportedOperationException
此時拋出的異常類型為:UnsupportedOperationException
指的是操作未實現(xiàn)異常烛谊,因為 of()
方法僅僅能夠創(chuàng)建一個固定大小的 List 實例风响。在實際開發(fā)中所使用的 List 集合一般都有具體的子類:ArrayList、Vector丹禀、LinkedList 三個常用子類状勤。