Collection架構
List
ArrayList
cloneable其實就是一個標記接口,只有實現這個接口後,然後在類中重寫Object中的clone方法,然後通過類調用clone方法才能克隆成功,如果不實現這個接口,則會拋出CloneNotSupportedException(克隆不被支持)異常。Object中clone方法:
protected native Object clone() throws CloneNotSupportedException;
RandomAccess在java.util.Collections#shuffle有用,源碼如下
JDK中推薦的是對List集合儘量要實現RandomAccess接口
如果集合類是RandomAccess的實現,則儘量用for(int i = 0; i < size; i++) 來遍歷而不要用Iterator迭代器來遍歷,在效率上要差一些。反過來,如果List是Sequence List,則最好用迭代器來進行迭代。
具體請點擊此博客
add
public boolean add(E e) {
//確定容量
ensureCapacityInternal(size + 1); // Increments modCount!!
//可存null
elementData[size++] = e;
return true;
}
private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
private static int calculateCapacity(Object[] elementData, int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
//初始化時,如設置的索引值<默認,則默認值
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
return minCapacity;
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
//如果當前索引>數組容量
if (minCapacity - elementData.length > 0)
//擴充容量
grow(minCapacity);
}
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
//擴充容量1.5倍
int newCapacity = oldCapacity + (oldCapacity >> 1);
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) {
//超過Int最大值,則異常
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
其他查找,修改,刪除
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;
}
public E set(int index, E element) {
rangeCheck(index);
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
public E remove(int index) {
rangeCheck(index);
modCount++;
E oldValue = elementData(index);
//如果不是最後一個元素,則調用native
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;
}
總結
ArrayList可以傳Null值
ArrayList擴容大小方法爲grow,每次擴容當前大小的一半的容量
ArrayList本質是一個elementData數組
arrayList實現了RandomAccess,所以在遍歷它的時候推薦使用for循環提升效率。
ArrayList繼承List接口,作者明確表示是一個意外,因爲AbstractList也繼承了
因爲本身是數組
所以查詢修改快,O(1)
刪除,插入因爲調用native方法,慢
LinkedList
因爲繼承了隊列接口,所以新增了pop,poll,push,peek,offer等方法
offer&add
public boolean offer(E e) {
return add(e);
}
public boolean add(E e) {
linkLast(e);
return true;
}
void linkLast(E e) {
final Node<E> l = last;
//創建新的node
final Node<E> newNode = new Node<>(l, e, null);
//賦值成最後的節點
last = newNode;
//如果last爲null,說明第一次賦值,則設置爲first
if (l == null)
first = newNode;
else
l.next = newNode;
size++;
modCount++;
}
push
public void push(E e) {
addFirst(e);
}
public void addFirst(E e) {
linkFirst(e);
}
/**
* Links e as first element.
* 添加到第一個節點
*/
private void linkFirst(E e) {
final Node<E> f = first;
//第一個值爲first,因爲當前節點設置爲first,所以null
final Node<E> newNode = new Node<>(null, e, f);
first = newNode;
//f爲null,說明第一次初始化,則最後的節點也是first
if (f == null)
last = newNode;
else
f.prev = newNode;
size++;
modCount++;
}
poll &remove
public E poll() {
final Node<E> f = first;
return (f == null) ? null : unlinkFirst(f);
}
private E unlinkFirst(Node<E> f) {
// assert f == first && f != null;
final E element = f.item;
final Node<E> next = f.next;
//釋放GC
f.item = null;
f.next = null; // help GC
first = next;
if (next == null)
last = null;
else
next.prev = null;
size--;
modCount++;
return element;
}
public E remove() {
return removeFirst();
}
public E removeFirst() {
final Node<E> f = first;
//爲null拋出異常
if (f == null)
throw new NoSuchElementException();
return unlinkFirst(f);
}
peek&element
public E peek() {
final Node<E> f = first;
return (f == null) ? null : f.item;
}
public E element() {
return getFirst();
}
public E getFirst() {
final Node<E> f = first;
//爲null則異常
if (f == null)
throw new NoSuchElementException();
return f.item;
}
remove
public boolean remove(Object o) {
//對null的處理
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;
}
E unlink(Node<E> x) {
// assert x != null;
final E element = x.item;
final Node<E> next = x.next;
final Node<E> prev = x.prev;
//first處理
if (prev == null) {
first = next;
} else {
prev.next = next;
x.prev = null;
}
//last處理
if (next == null) {
last = prev;
} else {
next.prev = prev;
x.next = null;
}
//釋放GC
x.item = null;
size--;
modCount++;
return element;
}
set
public E set(int index, E element) {
//index判斷
checkElementIndex(index);
//查找
Node<E> x = node(index);
//修改值
E oldVal = x.item;
x.item = element;
return oldVal;
}
Node<E> node(int index) {
// assert isElementIndex(index);
//如果小於node一半大小,從頭遍歷
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;
}
}
總結
維護頭尾2個node
查詢,index<size/2則first開始,否則last開始
可以存null
因爲採用鏈表數據結構存儲
所以查詢,修改慢 O(N)
插入,刪除快O(1)+O(N)
peek和poll針對null做了異常處理
Vector
public Vector() {
this(10);
}
public synchronized boolean add(E e) {
modCount++;
ensureCapacityHelper(elementCount + 1);
elementData[elementCount++] = e;
return true;
}
private void ensureCapacityHelper(int minCapacity) {
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
capacityIncrement : oldCapacity);
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
elementData = Arrays.copyOf(elementData, newCapacity);
}
默認10容量,且線程安全,因爲添加了方法級別的同步鎖,因爲鎖比較重量級,所以相對很少用的上.一般採用分段鎖,樂觀鎖來加鎖.
Set
HashSet
//底層維護hashMap
public HashSet() {
map = new HashMap<>();
}
public boolean add(E e) {
//利用hashMap存key,value存儲虛擬值
return map.put(e, PRESENT)==null;
}
public boolean remove(Object o) {
return map.remove(o)==PRESENT;
}
底層維護hashMap
利用PRESENT作爲value
LinkedHashSet
public LinkedHashSet() {
super(16, .75f, true);
}
HashSet(int initialCapacity, float loadFactor, boolean dummy) {
map = new LinkedHashMap<>(initialCapacity, loadFactor);
}
底層維護LinkedHashMap
TreeSet
利用PRESENT作爲value
底層維護TreeMap
總結
List和Set的區別在於是否唯一
如果存儲的值唯一
則Set
排序?
是:TreeSet,內部使用二叉樹
否:HashSet,數組+鏈表存儲,所以無序,但因此訪問速度O(1)+鏈表長度
否則List
增刪多:LinkedList
因爲底層鏈表的原因,所以修改的時候,只需要修改引用即可,所以O(1)
查詢多:ArrayList,線性表的原因,查詢速度很快