(总结)Java集合_1.List
参考:
ArrayList和LinkedList对比(性能分析和实现等)
类继承结构:
List
ArrayList与LinkedList的区别
-
继承: ArrayList类继承自AbstractList抽象类,实现了List接口;LinkedList类继承了AbstractSequentialList抽象类;同时LinkedList也继承了Deque接口,能够实现双端队列;
-
数据结构: Arraylist 底层使用的是可变容量的 Object 数组;LinkedList 底层使用的是 双向链表 数据结构(JDK1.6 之前为循环链表,JDK1.7 取消了循环。注意双向链表和双向循环链表的区别,下面有介绍到!)
-
对于随机访问,ArrayList要优于LinkedList;
-
对于插入和删除操作,LinkedList优于ArrayList;
-
插入和删除:
-
① ArrayList
-
add(E):直接在元素尾部添加元素,如果没有扩容,时间复杂度为O(1);
/** * Appends the specified element to the end of this list. * * @param e element to be appended to this list * @return <tt>true</tt> (as specified by {@link Collection#add}) */ public boolean add(E e) { ensureCapacityInternal(size + 1); // Increments modCount!! elementData[size++] = e; return true; }
-
add(int,E):在某个位置插入元素,需要将该索引之前所有的元素向后移以为,然后将元素放到数组的某个位置,如果没有扩容,时间复杂度主要为复制数组的代价;
/** * Inserts the specified element at the specified position in this * list. Shifts the element currently at that position (if any) and * any subsequent elements to the right (adds one to their indices). * * @param index index at which the specified element is to be inserted * @param element element to be inserted * @throws IndexOutOfBoundsException {@inheritDoc} */ public void add(int index, E element) { rangeCheckForAdd(index); ensureCapacityInternal(size + 1); // Increments modCount!! System.arraycopy(elementData, index, elementData, index + 1, size - index); elementData[index] = element; size++; }
-
get(int):获取某个位置下的元素,时间复杂度为O(1);
public E get(int index) { rangeCheck(index); return elementData(index); }
-
set(int):类似于get,时间复杂度为O(1);
public E set(int index, E element) { rangeCheck(index); E oldValue = elementData(index); elementData[index] = element; return oldValue; }
-
remove(int):删除某个位置上的元素,也是需要移动索引位置后面所有的元素;
/** * Removes the element at the specified position in this list. * Shifts any subsequent elements to the left (subtracts one from their * indices). * * @param index the index of the element to be removed * @return the element that was removed from the list * @throws IndexOutOfBoundsException {@inheritDoc} */ public E remove(int index) { rangeCheck(index); modCount++; E oldValue = elementData(index); int numMoved = size - index - 1; if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--size] = null; // clear to let GC do its work return oldValue; }
-
remove(Object):移除某个特定元素,有相同对象则移除遇到的第一个,返回true,分两种情况:
①如果要移除的对象为空,则找到elementData中第一次出现空对象的位置,如果有,则返回true,否则返回false;
②如果要移除的对象不是空,那么则可以直接调用equals方法进行比较。在这里之所以这么麻烦分两步是因为,数组中有可能有空的对象,所以不能调用elementData.equals()方法,另外,传入的对象也可能为空,一样不能直接调用equals()方法。性能方面,该方法多出了一步是判断,并且需要遍历整个数组,O(n);/** * Removes the first occurrence of the specified element from this list, * if it is present. If the list does not contain the element, it is * unchanged. More formally, removes the element with the lowest index * <tt>i</tt> such that * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt> * (if such an element exists). Returns <tt>true</tt> if this list * contained the specified element (or equivalently, if this list * changed as a result of the call). * * @param o element to be removed from this list, if present * @return <tt>true</tt> if this list contained the specified element */ public boolean remove(Object o) { if (o == null) { for (int index = 0; index < size; index++) if (elementData[index] == null) { fastRemove(index); return true; } } else { for (int index = 0; index < size; index++) if (o.equals(elementData[index])) { fastRemove(index); return true; } } return false; }
-
-
② LinkedList
-
add(E):默认在链表末尾插入,时间复杂度O(1);
/** * Appends the specified element to the end of this list. * * <p>This method is equivalent to {@link #addLast}. * * @param e element to be appended to this list * @return {@code true} (as specified by {@link Collection#add}) */ public boolean add(E e) { linkLast(e); return true; } /** * Links e as last element. */ void linkLast(E e) { final Node<E> l = last; final Node<E> newNode = new Node<>(l, e, null); last = newNode; if (l == null) first = newNode; else l.next = newNode; size++; modCount++; }
-
addFirst(E),addLast(E):选择在头或者尾插入,时间复杂度O(1);
public void addFirst(E e) { linkFirst(e); } public void addLast(E e) { linkLast(e); } private void linkFirst(E e) { final Node<E> f = first; final Node<E> newNode = new Node<>(null, e, f); first = newNode; if (f == null) last = newNode; else f.prev = newNode; size++; modCount++; }
-
add(int, E):需要找到索引的位置,然后再在链表中插入。在查找索引位置的时候,利用头结点和尾节点,根据索引值和size大小的比较,判断是从头开始遍历还是从尾开始遍历(空间换时间,一个变量就可以减少一半的搜索操作了)。使用该方法,那么add方法的效率则要多出一部分花在查找元素上。
/** * Inserts the specified element at the specified position in this list. * Shifts the element currently at that position (if any) and any * subsequent elements to the right (adds one to their indices). * * @param index index at which the specified element is to be inserted * @param element element to be inserted * @throws IndexOutOfBoundsException {@inheritDoc} */ public void add(int index, E element) { checkPositionIndex(index); if (index == size) linkLast(element); else linkBefore(element, node(index)); }
-
get(int): 和通过索引插入元素一样,都需要遍历一半的列表来找到元素;
public E get(int index) { checkElementIndex(index); return node(index).item; } /** * Returns the (non-null) Node at the specified element index. */ Node<E> node(int index) { // assert isElementIndex(index); if (index < (size >> 1)) { Node<E> x = first; for (int i = 0; i < index; i++) x = x.next; return x; } else { Node<E> x = last; for (int i = size - 1; i > index; i--) x = x.prev; return x; } }
-
set(int,E): 修改某个索引下的值,仍然需要找到元素之后再进行修改;
public E set(int index, E element) { checkElementIndex(index); Node<E> x = node(index); E oldVal = x.item; x.item = element; return oldVal; }
-
remove(Object): 从头进行查找匹配,时间复杂度O(n),但是相对于ArrayList少了数组拷贝的时间;
public boolean remove(Object o) { if (o == null) { for (Node<E> x = first; x != null; x = x.next) { if (x.item == null) { unlink(x); return true; } } } else { for (Node<E> x = first; x != null; x = x.next) { if (o.equals(x.item)) { unlink(x); return true; } } } return false; }
-
ArrayList扩容机制
1. ArrayList初始化方式:
- public ArrayList() :无参数构造,默认构造函数,以无参数构造方法创建 ArrayList 时,实际上初始化赋值的是一个空数组。当真正对数组进行添加元素操作时,才真正分配容量。即向数组中添加第一个元素时,数组容量扩为10;
- public ArrayList(int initialCapacity):带初始容量参数的构造函数;
- public ArrayList(Collection<? extends E> c):传入指定collection元素的列表,这些元素利用该集合的迭代器按顺序返回存入ArrayList;
源码:
/**
* 默认初始容量大小
*/
private static final int DEFAULT_CAPACITY = 10;
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
/**
*默认构造函数,使用初始容量10构造一个空列表(无参数构造)
*/
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
/**
* 带初始容量参数的构造函数。(用户自己指定容量)
*/
public ArrayList(int initialCapacity) {
if (initialCapacity > 0) {//初始容量大于0
//创建initialCapacity大小的数组
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {//初始容量等于0
//创建空数组
this.elementData = EMPTY_ELEMENTDATA;
} else {//初始容量小于0,抛出异常
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}
/**
*构造包含指定collection元素的列表,这些元素利用该集合的迭代器按顺序返回
*如果指定的集合为null,throws NullPointerException。
*/
public ArrayList(Collection<? extends E> c) {
elementData = c.toArray();
if ((size = elementData.length) != 0) {
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
} else {
// replace with empty array.
this.elementData = EMPTY_ELEMENTDATA;
}
}
2. 分析 ArrayList 扩容机制:
-
add 方法:
/** * 将指定的元素追加到此列表的末尾。 */ public boolean add(E e) { //添加元素之前,先调用ensureCapacityInternal方法 ensureCapacityInternal(size + 1); // Increments modCount!! //这里看到ArrayList添加元素的实质就相当于为数组赋值 elementData[size++] = e; return true; }
-
ensureCapacityInternal() 方法:当要add进第1个元素时,minCapacity为1,在Math.max()方法比较后,minCapacity 为10;
//得到最小扩容量 private void ensureCapacityInternal(int minCapacity) { if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { // 获取默认的容量和传入参数的较大值 minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity); } ensureExplicitCapacity(minCapacity); }
-
ensureExplicitCapacity() 方法:
//判断是否需要扩容 private void ensureExplicitCapacity(int minCapacity) { modCount++; // overflow-conscious code if (minCapacity - elementData.length > 0) //调用grow方法进行扩容,调用此方法代表已经开始扩容了 grow(minCapacity); }
我们来仔细分析一下:
- 当我们要 add 进第1个元素到 ArrayList 时,elementData.length 为0 (因为还是一个空的 list),因为执行了 ensureCapacityInternal() 方法 ,所以 minCapacity 此时为10。此时,minCapacity - elementData.length > 0 成立,所以会进入 grow(minCapacity) 方法。
- 当add第2个元素时,minCapacity 为2,此时e lementData.length(容量)在添加第一个元素后扩容成 10 了。此时,minCapacity - elementData.length > 0 不成立,所以不会进入 (执行)grow(minCapacity) 方法。
- 添加第3、4···到第10个元素时,依然不会执行grow方法,数组容量都为10。
- 直到添加第11个元素,minCapacity(为11)比elementData.length(为10)要大。进入grow方法进行扩容。
-
grow()方法:
/** * 要分配的最大数组大小 */ private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; /** * ArrayList扩容的核心方法。 */ private void grow(int minCapacity) { /* oldCapacity为旧容量,newCapacity为新容量*/ int oldCapacity = elementData.length; /*将oldCapacity 右移一位,其效果相当于oldCapacity /2, *我们知道位运算的速度远远快于整除运算,整句运算式的结果就是将新容量更新为旧容量的1.5倍, */ int newCapacity = oldCapacity + (oldCapacity >> 1); /*然后检查新容量是否大于最小需要容量,若还是小于最小需要容量, *那么就把最小需要容量当作数组的新容量 */ if (newCapacity - minCapacity < 0) newCapacity = minCapacity; /* 如果新容量大于 MAX_ARRAY_SIZE,进入(执行) `hugeCapacity()` 方法来比较 minCapacity 和 * MAX_ARRAY_SIZE, * 如果minCapacity大于最大容量,则新容量则为`Integer.MAX_VALUE`,否则,新容量大小则为 * MAX_ARRAY_SIZE 即为 `Integer.MAX_VALUE - 8`。 */ if (newCapacity - MAX_ARRAY_SIZE > 0) newCapacity = hugeCapacity(minCapacity); /* minCapacity is usually close to size, so this is a win:*/ elementData = Arrays.copyOf(elementData, newCapacity); }
总结:
所以 ArrayList 每次扩容之后容量都会变为原来的 1.5 倍左右(oldCapacity为偶数就是1.5倍,否则是1.5倍左右)! 奇偶不同,比如 :10+10/2 = 15, 33+33/2=49。如果是奇数的话会丢掉小数.