2021-05-22
List 接口定义:
public interface List<E> extends Collection<E>
虽然 List 是 Collection 接口的子接口,但是 List 接口本身会提供有许多新的处理方法,这些方法是扩展来的,有如下几个重要的扩展方法:
方法 | 描述 |
---|---|
void add(int index, E element) | 在指定索引位置处添加元素 |
E get(int index) |
根据索引获取保存的数据 |
int indexOf(Object o) | 获取指定数据的索引位置 |
ListIterator<E> listIterator() | 获取 ListIterator 接口对象实例 |
E set(int index, E element) | 修改指定索引位置的数据 |
default void sort(Comparator<? super E> c) | 使用特定比较器实现排序操作 |
List<E> subList(int fromIndex, int toIndex) | 截取子集合 |
@SafeVarargs static <E> List<E> of(E... elements) | [Since 9] 通过给定元素创建 List 集合 |
使用 of() 方法实现 List 集合创建
public class ListDemo {
public static void main(String[] args) {
// 此时所创建的 List 集合内部存在重复的数据内容
List all = List.of("Jade", "Bamboo", "Lemon", "Jade");
System.out.println(all);
for (Object obj : all.toArray()) {
System.out.println(obj);
}
}
}
以上的 List 集合从严格意义上来讲是属于一种半成品的工具类,如果此时执行的一下的程序代码,则会抛出异常:
List all = List.of("Jade", "Bamboo", "Lemon", "Jade");
all.add("wust"); // Exception in thread "main" java.lang.UnsupportedOperationException
此时抛出的异常类型为:UnsupportedOperationException
指的是操作未实现异常,因为 of()
方法仅仅能够创建一个固定大小的 List 实例。在实际开发中所使用的 List 集合一般都有具体的子类:ArrayList、Vector、LinkedList 三个常用子类。
List 接口