List
- ArrayList:基于动态数组实现,支持随机访问。
- Vector:和 ArrayList 类似,但它是线程安全的。
- LinkedList:基于双向链表实现,只能顺序访问,但是可以快速地在链表中间插入和删除元素。不仅如此,LinkedList 还可以用作栈、队列和双向队列。
为什么要先继承AbstractList?
这里是有一个思想,接口中全都是抽象的方法,而抽象类中可以有抽象方法,还可以有具体的实现方法,如ArrayList就继承这个AbstractList类,拿到一些通用的方法,然后自己在实现一些自己特有的方法,这样一来,让代码更简洁,就继承结构最底层的类中通用的方法都抽取出来,先一起实现了,减少重复代码。所以一般看到一个类上面还有一个抽象类,应该就是这个作用。
一、ArrayList源码分析
1.成员变量
/*默认容量*/
private static final int DEFAULT_CAPACITY = 10;
/*空数组*/
private static final Object[] EMPTY_ELEMENTDATA = {};
/*默认空对象数据*/
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
/*元素数组*/
transient Object[] elementData;
/*实际存储元素个数*/
private int size;
/*最大容量*/
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
2.构造方法
- 无参构造
//无参构造,元素数组等于默认空对象数组
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
- 指定容量
// 指定容量
public ArrayList(int initialCapacity) {
if (initialCapacity > 0) {
// 创建新数组
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {
// 指定为0,同无参一样使用默认空数组
this.elementData = EMPTY_ELEMENTDATA;
} else {
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}
- 传入指定Collection对象
public ArrayList(Collection<? extends E> c) {
elementData = c.toArray();
if ((size = elementData.length) != 0) {
/*每个集合的toarray()的实现方法不一样,所以需要判断一下,如果不是Object[].class类型,那么就需要使用ArrayList中的方法去改造一下。*/
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
} else {
/* 如果数组的实际大小等于0(c中没有元素),将空数组EMPTY_ELEMENTDATA赋值给elementData */
this.elementData = EMPTY_ELEMENTDATA;
}
}
3.核心方法
1)添加方法
- add(E)
public boolean add(E e) {
/* 确定内部容量是否够,size是当前数组中数据的个数,所以size+1,判断数组能否放下要添加的数据 */
ensureCapacityInternal(size + 1);
// 将数据添加至末尾
elementData[size++] = e;
return true;
}
- add(int,E)
public void add(int index, E element) {
// 检查index是否越界的函数(<0或者大于size)
rangeCheckForAdd(index);
// 同add,确保能够放下
ensureCapacityInternal(size + 1);
// 将元素后移,腾出index的位置
System.arraycopy(elementData, index, elementData, index + 1, size - index);
// 添加的元素放到index
elementData[index] = element;
// 元素个数加1
size·++;
}
- addAll(Collection)
public boolean addAll(Collection<? extends E> c) {
// 将C转化为数组
Object[] a = c.toArray();
// 获取数组长度
int numNew = a.length;
// 判断容量是否够加入numNew个元素
ensureCapacityInternal(size + numNew);
// 将c中的元素拷贝到数组中
System.arraycopy(a, 0, elementData, size, numNew);
// 添加numNew个元素
size += numNew;
return numNew != 0;
}
-
addAll(int,Collection)
与上面一样,只是多了一个移动数据的过程
2)查找方法
- get()
public E get(int index) {
// 判断index是否越界
rangeCheck(index);
// 返回数组中下标为index的元素
return elementData(index);
}
E elementData(int index) {
return (E) elementData[index];
}
- indexOf(Object)
// 返回目标元素的下标,不存在就返回-1
public int indexOf(Object o) {
if (o == null) {
for (int i = 0; i < size; i++)
if (elementData[i]==null)
return i;
} else {
for (int i = 0; i < size; i++)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
-
lastIndexOf(Object)
逻辑和indexOf一样,只不过是倒序遍历
-
contains(Object)
// 通过index来判断是否存在
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
3)修改方法
public E set(int index, E element) {
rangeCheck(index);
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
4)删除方法
- remove(int)
public E remove(int index) {
// 检查index是否越界
rangeCheck(index);
modCount++;
// 获取被删除元素
E oldValue = elementData(index);
int numMoved = size - index - 1;
// 将后面的元素前移
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
// 清除最后一个元素,size-1
elementData[--size] = null;
// 返回被删除的值
return oldValue;
}
- remove(Object)
public boolean remove(Object o) {
// o为null和o不为null都是通过fastRemove来进行删除
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;
}
// 和remove类似,只是不再返回被删除元素
private void fastRemove(int index) {
modCount++;
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null;
}
- clear()
public void clear() {
modCount++;
// 循环置空
for (int i = 0; i < size; i++)
elementData[i] = null;
// size设置为0
size = 0;
}
- removeRange(int,int)
// 删除范围内的元素,左闭右开
protected void removeRange(int fromIndex, int toIndex) {
modCount++;
// toIndex后面的元素个数
int numMoved = size - toIndex;
// 将toIndex后面的元素从formIndex处一一覆盖
System.arraycopy(elementData, toIndex, elementData, fromIndex,
numMoved);
// 新数组长度
int newSize = size - (toIndex-fromIndex);
// 循环将size后面的废弃元素置空
for (int i = newSize; i < size; i++) {
elementData[i] = null;
}
size = newSize;
}
- removeAll(Collection)
public boolean removeAll(Collection<?> c) {
// 调用Object的方法,如果c为null,抛出空指针异常
Objects.requireNonNull(c);
return batchRemove(c, false);
}
/*这个方法,用于两处地方,如果complement为false,则用于removeAll如果为true,则给retainAll()用,retainAll()是用来检测两个集合是否有交集的 */
private boolean batchRemove(Collection<?> c, boolean complement) {
final Object[] elementData = this.elementData;
int r = 0, w = 0;
boolean modified = false;
try {
for (; r < size; r++)
if (c.contains(elementData[r]) == complement)
elementData[w++] = elementData[r];
} finally {
// Preserve behavioral compatibility with AbstractCollection,
// even if c.contains() throws.
if (r != size) {
System.arraycopy(elementData, r,
elementData, w,
size - r);
w += size - r;
}
if (w != size) {
// clear to let GC do its work
for (int i = w; i < size; i++)
elementData[i] = null;
modCount += size - w;
size = w;
modified = true;
}
}
return modified;
}
扩容分析
private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
private static int calculateCapacity(Object[] elementData, int minCapacity) {
/* 判断是否为默认空数组,如果是空数组,说明没有长度,存放不了,然后返回默认容量和size+1中的max值 */
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
return minCapacity;
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
/* 如果calculateCapacity返回的值大于数组长度,则说明数组容量不够,进行扩容*/
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
private void grow(int minCapacity) {
int oldCapacity = elementData.length;
// newCapacity = 1.5oldCapacity
int newCapacity = oldCapacity + (oldCapacity >> 1);
/*如果是空数组第一次添加,那么new = old都是0,所以这里要进行处理*/
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
// 如果大于最大容量, 那么通过hugeCapacity进行大容量分配
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// 扩容完成,拷贝数组
elementData = Arrays.copyOf(elementData, newCapacity);
}
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
总结
1)ArrayList可以存放null。
2)ArrayList本质上就是一个Object数组。
3)ArrayList区别于数组的地方在于能够自动扩展大小,其中关键的方法就是gorw()方法。
4)ArrayList实现了RandomAccess,所以在遍历它的时候推荐使用for循环和增强for循环
二、LinkedList源码分析
LinkedList是用链表实现的List。其内部维护了一个Node双向链表:
// 静态内部类
private static class Node<E> {
E item;
Node<E> next;
Node<E> prev;
Node(Node<E> prev, E element, Node<E> next) {
this.item = element;
this.next = next;
this.prev = prev;
}
}
1.成员变量
/* 存储元素个数*/
transient int size = 0;
/* 头结点 */
transient Node<E> first;
/* 尾结点 */
transient Node<E> last;
2.构造方法
- 无参构造
public LinkedList() {
}
- 传入指定Collection对象
/* 包含Collection的构造方法,先调用无参构造方法建立一个空链表,而后将Collection中的数据加入到链表的尾部后面 */
public LinkedList(Collection<? extends E> c) {
this();
addAll(c);
}
3.核心方法
1)添加方法
- add(E)
public boolean add(E e) {
linkLast(e);
return true;
}
// add通过该方法实现
void linkLast(E e) {
final Node<E> l = last;
// 创建一个新节点,pre为last节点
final Node<E> newNode = new Node<>(l, e, null);
// 将last节点指向新节点(新的队尾)
last = newNode;
// 如果last为null,说明last=head=null,链表为空
if (l == null)
// 新节点为头结点
first = newNode;
else
// 否则将原队尾的next指向新节点
l.next = newNode;
size++;
modCount++;
}
- add(int,E)
public void add(int index, E element) {
// 检查index是否越界
checkPositionIndex(index);
// 如果index正好指向队尾,直接添加
if (index == size)
linkLast(element);
else
// 首先调用node方法将index位置的节点找出,接着调用linkBefore
linkBefore(element, node(index));
}
void linkBefore(E e, Node<E> succ) {
// succ为index位置上的节点
final Node<E> pred = succ.prev;
// 创建要插入的新节点,pre为index-1上的元素
final Node<E> newNode = new Node<>(pred, e, succ);
// 将原index位置元素的pre指向新节点(即向后移)
succ.prev = newNode;
// 如果index-1位置上是null,则说明index是头结点
if (pred == null)
first = newNode;
else
// 将index-1位置的next指向新节点
pred.next = newNode;
size++;
modCount++;
}
-
addAll(Collection)
逻辑类似于ArrayList
-
addAll(int,Collection)
逻辑类似于ArrayList
-
addFirst(E)
public void addFirst(E e) {
linkFirst(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++;
}
- addLast(E)
// 同addFirst一样,逻辑简单
public void addLast(E e) {
linkLast(e);
}
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++;
}
2)查找方法
- get(index)
public E get(int index) {
// 查看下标是否越界
checkElementIndex(index);
// 返回index处Node的item
return node(index).item;
}
- getFirst()
// 返回first
public E getFirst() {
final Node<E> f = first;
if (f == null)
throw new NoSuchElementException();
return f.item;
}
- getLast()
// 返回last
public E getLast() {
final Node<E> l = last;
if (l == null)
throw new NoSuchElementException();
return l.item;
}
- indexOf(Object)
// 遍历获取,没有则返回-1有则返回对应的index值
public int indexOf(Object o) {
int index = 0;
if (o == null) {
for (Node<E> x = first; x != null; x = x.next) {
if (x.item == null)
return index;
index++;
}
} else {
for (Node<E> x = first; x != null; x = x.next) {
if (o.equals(x.item))
return index;
index++;
}
}
return -1;
}
-
lastIndexOf(Object)
逻辑同上,只是改为倒序遍历
3)修改方法
- set(int,E)
public E set(int index, E element) {
// 检查index是否越界
checkElementIndex(index);
Node<E> x = node(index);
E oldVal = x.item;
// 替换旧值
x.item = element;
// 返回旧值
return oldVal;
}
4)删除方法
- remove()和removeFirst()
// remove方法删除的是头结点
public E remove() {
return removeFirst();
}
public E removeFirst() {
final Node<E> f = first;
if (f == null)
throw new NoSuchElementException();
return unlinkFirst(f);
}
private E unlinkFirst(Node<E> f) {
// assert f == first && f != null;
final E element = f.item;
final Node<E> next = f.next;
f.item = null;
f.next = null; // help GC
first = next;
if (next == null)
last = null;
else
next.prev = null;
size--;
modCount++;
return element;
}
- removeLast()
public E removeLast() {
final Node<E> l = last;
if (l == null)
throw new NoSuchElementException();
return unlinkLast(l);
}
- remove(Object)和remove(int)
// 循环遍历链表进行删除
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;
}
// 先检查index越界问题,在进行节点的unlink
public E remove(int index) {
checkElementIndex(index);
return unlink(node(index));
}
// 将节点的前后节点进行关联,然后该节点置为null
E unlink(Node<E> x) {
final E element = x.item;
final Node<E> next = x.next;
final Node<E> prev = x.prev;
if (prev == null) {
first = next;
} else {
prev.next = next;
x.prev = null;
}
if (next == null) {
last = prev;
} else {
next.prev = prev;
x.next = null;
}
x.item = null;
size--;
modCount++;
return element;
}
-
removeFirstOccurrence(Object)和removeLastOccurrence(Object)
分别为删除第一次出现和最后一次出现
public boolean removeFirstOccurrence(Object o) {
return remove(o);
}
// 倒序遍历
public boolean removeLastOccurrence(Object o) {
if (o == null) {
for (Node<E> x = last; x != null; x = x.prev) {
if (x.item == null) {
unlink(x);
return true;
}
}
} else {
for (Node<E> x = last; x != null; x = x.prev) {
if (o.equals(x.item)) {
unlink(x);
return true;
}
}
}
return false;
}
总结
1)可以存放null
2)基于内部类Node维护链表
3)推荐使用增强for循环或迭代器遍历
三、Vector
Vector的方法实现几乎与ArrayList一样,只不过Vector的方法都加了synchronized来保证线程安全
四、Vector与ArrayList对比
- 扩容大小不同:ArrayList是1.5倍而Vector是2倍(capacityIncrement为0的时候)
- Vector可以通过capacityIncrement参数设置扩容大小
- Vector线程安全而ArrayList不是
五、迭代器
List和Set都有iterator()来取得其迭代器。对List来说,也可以通过listIterator()取得其迭代器,Iterator和ListIterator主要区别在以下方面:
- ListIterator有add()方法,可以向List中添加对象,而Iterator不能
- ListIterator和Iterator都有hasNext()和next()方法,可以实现顺序向后遍历,但是ListIterator有hasPrevious()和previous()方法,可以实现逆向(顺序向前)遍历。Iterator就不可以。
- ListIterator可以定位当前的索引位置,nextIndex()和previousIndex()可以实现。Iterator没有此功能。
- 都可实现删除对象,但是ListIterator可以实现对象的修改,set()方法可以实现。Iierator仅能遍历,不能修改。