java集合之 ArrayList
阿新 • • 發佈:2018-12-10
通過本文你將瞭解到 ArrayList 的如下資訊
目錄
batchRemove(Collection c, boolean complement):保留或者刪除 c 集合中所包含的元素
set(int index, E element):修改指定位置的元素
ArrayList 簡介
ArrayList 是一個可儲存包括 null 值的任意型別資料、支援動態擴容、有序(輸入順序與輸出順序一致)、查詢效率高(時間複雜度O(1))的一個集合。
ArrayList原始碼分析
重要成員變數
底層資料結構:陣列
//儲存元素
transient Object[] elementData; // non-private to simplify nested class access
transient表示不允許被序列化
預設初始容量:10
private static final int DEFAULT_CAPACITY = 10;
當前元素個數
private int size;
重要方法
add(E e): 新增一個元素
public boolean add(E e) { //確保有足夠的容量 ensureCapacityInternal(size + 1); // Increments modCount!! //在 size 下標處新增一個元素 elementData[size++] = e; return true; } private void ensureCapacityInternal(int minCapacity) { if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { //當前所需要的最小容量大於等於 10 minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity); } ensureExplicitCapacity(minCapacity); } private void ensureExplicitCapacity(int minCapacity) { modCount++; // 當前儲存空間(陣列容量)不夠了 if (minCapacity - elementData.length > 0) grow(minCapacity); }
簡單描述:空間是否足夠儲存--->如果不夠就進行擴容--->儲存資料到 size 處
grow(int minCapacity):擴容
在沒有達到邊界值的情況下,擴容後的陣列容量 = 舊陣列容量+舊陣列容量/2
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
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);
}
batchRemove(Collection<?> c, boolean complement):保留或者刪除 c 集合中所包含的元素
根據 complement 來決定是保留還是移除指定集合中存在的元素
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++)
//complement為true:保留 elementData 和 c 中都存在的元素(相當於求交集)
//complement為false:保留只存在於 elementaData 中,但是不存在於c中的元素
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;
}
set(int index, E element):修改指定位置的元素
public E set(int index, E element) {
rangeCheck(index);
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
get(int index) :查詢指定位置的元素
public E get(int index) {
rangeCheck(index);
return elementData(index);
}
遍歷
ArrayList 內部實現了兩種迭代器(Itr、ListItr)來遍歷元素。本質都是根據陣列下標來操作的
private class Itr implements Iterator<E> {
int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount;
public boolean hasNext() {
return cursor != size;
}
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
@Override
@SuppressWarnings("unchecked")
public void forEachRemaining(Consumer<? super E> consumer) {
Objects.requireNonNull(consumer);
final int size = ArrayList.this.size;
int i = cursor;
if (i >= size) {
return;
}
final Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length) {
throw new ConcurrentModificationException();
}
while (i != size && modCount == expectedModCount) {
consumer.accept((E) elementData[i++]);
}
// update once at end of iteration to reduce heap write traffic
cursor = i;
lastRet = i - 1;
checkForComodification();
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
/**
* An optimized version of AbstractList.ListItr
*/
private class ListItr extends Itr implements ListIterator<E> {
ListItr(int index) {
super();
cursor = index;
}
public boolean hasPrevious() {
return cursor != 0;
}
public int nextIndex() {
return cursor;
}
public int previousIndex() {
return cursor - 1;
}
@SuppressWarnings("unchecked")
public E previous() {
checkForComodification();
int i = cursor - 1;
if (i < 0)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i;
return (E) elementData[lastRet = i];
}
public void set(E e) {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.set(lastRet, e);
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
public void add(E e) {
checkForComodification();
try {
int i = cursor;
ArrayList.this.add(i, e);
cursor = i + 1;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
}
總結
上面通過增刪改查四個具有代表性的方法分析了ArrayList 原始碼,ArrayList中的其它方法其實也是類似的,所以沒有羅列出來。想要表達的中心思想是:ArrayList 底層資料結構是採用的是陣列,所以對於查詢會很快(直接根據陣列下標),刪除會比較滿(會涉及到元素的移動)。對於陣列的遍歷,建議直接使用 for 迴圈,根據陣列下標直接獲取。