ArrayList和LinkedList的区别
在查找API可以发现,ArrayList类和LinkedList类都在java.util包中。下面介绍两者的区别和适用的场景。
ArrayList类和LinkedList类区别简介:(看源码)
1. ArrayList是实现了基于动态数组的数据结构,LinkedList是基于链表结构。
- 而之所以称为动态数组,是因为Arraylist在数组元素超过其容量大,Arraylist可以进行扩容(针对JDK1.8 数组扩容后的容量是扩容前的1.5倍),Arraylist源码中最大的数组容量是Integer.MAX_VALUE-8。
2. 对于随机访问的get和set方法,ArrayList要优于LinkedList,因为LinkedList要移动指针。
3. 对于新增和删除操作add和remove,LinkedList比较占优势,因为ArrayList要移动数据。
下面分析ArrayList部分源码:
1. ArrayList扩容:
(其中汉字部分为本人注释)
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
/**
* Increases the capacity to ensure that it can hold at least the
* number of elements specified by the minimum capacity argument.
*
* @param minCapacity the desired minimum capacity
*/
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);//扩充后的容量(>>表示向右移位,相当于除以2)
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
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);
}
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;//当Integer.MAX_VALUE - 8无法满足内存要求时,就设容量为Integer.MAX_VALUE
}
2. 下面分析LinkedList部分源码:访问数据的源码:(node()函数遍历链表)
public E get(int index) {
checkElementIndex(index);
return node(index).item;
}
/////////////
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;
}
}