List

[TOC]

List方法

list_method

位置访问方法

1
2
3
4
5
6
void (int index, E e) 
boolean addAll(int index, Collection<? extends E> c)
// add contents of c at given index
E get(int index) // return element with given index
E remove(int index) // remove element with given index
E set(int index, E e) // replace element with given index by e

查找

1
2
int indexOf(Object o) // return index of first occurrence of o
int lastIndexOf(Object o) // return index of last occurrence of o

范围查看

1
2
List<E> subList(int fromIndex, int toIndex)
// return a view of a portion of the list

ps:subList返回视图,对视图的修改会作用与母List,
若对母List做修改,访问子视图会报ConcurrentModificationException

List迭代器

1
2
3
4
5
ListIterator<E> listIterator() // return a ListIterator for this list,
// initially positioned at index 0
ListIterator<E> listIterator(int indx)
// return a ListIterator for this list,
// initially positioned at index indxs

ListIterator新增加的方法

1
2
3
4
5
6
7
public interface ListIterator<E> extends Iterator<E> {
void (E e); // 在游标 前面 插入一个元素(注意,是前面)
boolean hasPrevious(); // 判断游标前面是否有元素
int nextIndex(); // 返回游标后边元素的索引位置,初始为 0 
E previous(); // 返回游标前面的元素,同时游标前移一位。游标前没有元素就报 java.util.NoSuchElementException 的错
int previousIndex(); // 返回游标前面元素的位置,初始时为 -1,同时报 java.util.NoSuchElementException 错;
void set(E e); // r更新迭代器最后一次操作的元素为 E,也就是更新最后一次调用 next() 或者 previous() 返回的元素。当没有迭代,也就是没有调用 next() 或者 previous() 直接调用 set 时会报 java.lang.IllegalStateException 错

List实现

implementation_of_the_list_interface.png

ArrayList

get、set快
remove、insert慢
初始化空间:默认10,复制其他数组(开辟该数组空间的)110%
扩展(原数组大小+原数组大小/2)

LinkedList

末尾以外的地方添加、删除快
大量查找(随机访问)慢

CopyOnWriteArrayList

写时复制,适用于读多写少

1
addIfAbsent()//添加元素如果不存在

线程安全

List实现对比

Comparative.png