List可能是大部分使用者最先接触到的集合类型,提供了较为简单的实现,实现数据的处理。
List是有顺序的、可重复的、元素可为null的集合。存储内容时直接在内存中开辟一块连续的空间,然后将空间地址与索引相对应。
下面是List中较之Collection新定义的一些方法:
- replaceAll方法
default void replaceAll(UnaryOperator<E> operator) {
Objects.requireNonNull(operator);
final ListIterator<E> li = this.listIterator();
while (li.hasNext()) {
li.set(operator.apply(li.next()));
}
}
1.8中出现的新方法,接收lambda表达式生成的一个UnaryOperator对象,对list中的每个对象进行替换操作
一个简单的例子:
List<String> list = new ArrayList<>();
list.add("hello");
list.add("notebook");
list.replaceAll(s -> s.replace("e", "E"));
System.out.println(list.toString());
//输出
[hEllo, notEbook]
- sort方法
@SuppressWarnings({"unchecked", "rawtypes"})
default void sort(Comparator<? super E> c) {
Object[] a = this.toArray();
Arrays.sort(a, (Comparator) c);
ListIterator<E> i = this.listIterator();
for (Object e : a) {
i.next();
i.set((E) e);
}
}
1.8中新增的方法,让list的调用自己的方法就能实现排序,不必再实现comparable接口或者使用Collections类的排序方法进行排序,其实底层调用了Arrays方法对list进行排序,方法同样支持lambda的函数式编程,下面是一个小例子:
List<Integer> list = new ArrayList<>();
for (int i = 10; i > 0; i--) {
list.add(i);
}
System.out.println(list);
list.sort((o1, o2) -> o1 - o2);
// Collections.sort(list);//与上一行作用相同
System.out.println(list);
//输出
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
E get(int index);
作用:根据下表获取list中的元素
返回:指定下标出的元素
异常:给定下标如果不在list的范围之内,报IndexOutOfBoundsException异常E set(int index, E element)
作用:设置list的指定下标处的元素
返回:返回的是之前在指定下标出的元素
异常:
- @throws UnsupportedOperationException if the <tt>set</tt> operation
- is not supported by this list
- @throws ClassCastException if the class of the specified element
- prevents it from being added to this list
- @throws NullPointerException if the specified element is null and
- this list does not permit null elements
- @throws IllegalArgumentException if some property of the specified
- element prevents it from being added to this list
- @throws IndexOutOfBoundsException if the index is out of range
1、list的实现类不支持set操作的时候,报UnsupportedOperationException 异常
2、如果参数元素的类型被禁止加入到集合中时,报ClassCastException 异常
3、指定元素为null但list不允许出现null元素时,报NullPointerException 异常
4、指定元素的一些属性导致元素不能被添加到list中时,报IllegalArgumentException 异常
5、指定的下标超出list的范围时,报IndexOutOfBoundsException 异常
void add(int index, E element);
作用:添加指定元素到list的指定位置,如果指定位置已有元素,则将指定元素右移
参数,异常跟set方法一样E remove(int index)
作用:删除指定位置的元素
返回:删除前指定位置上的元素
异常:
1、list的实现类不支持remove操作的时候,报UnsupportedOperationException 异常
2、指定的下标超出list的范围时,报IndexOutOfBoundsException 异常int indexOf(Object o)
作用:获取指定元素第一次出现的下标
返回:指定元素第一次出现的下标
异常:
1、参数元素的类型与list指定的泛型类型不同时,报ClassCastException 异常
2、指定元素为null但list不允许出现null元素时,报NullPointerException 异常int lastIndexOf(Object o)
参数:想要查找的元素
作用、返回、异常与indexOf方法类似ListIterator listIterator();ListIterator listIterator(int index)
list特有的迭代器,第一个方法返回元顺序的迭代器,第二个返回从指定下标开始的迭代器List subList(int fromIndex, int toIndex);
作用:获取list的一个子list
参数:fromIndex 开始下标 toIndex结束下标
返回:与之前list类型完全相同的子list
异常:开始下标小于0、结束下标大于list的size、开始下标大于结束下标时,报IndexOutOfBoundsException