集合框架总结
? 2019作為新的一年開始,我也著手面試的準備。這篇的博客的主角集合--面試中都會出現的,所以今天特作此總結,也算是復習的成果的一個展示。在查看了許多的博客和源碼后我決定將其分成3部分來總結。
三個部分分別是:集合的分類、各個集合的底層實現、集合方法的源碼實現
集合的分類
1.集合--?collection接口
?
??
先上個圖
collection作為Set, List, Queue三個接口的父接口,它定義了操作集合的公用方法,包括add(),remove()等方法。稍后會對這些常用的方法進行源碼解讀。集合作為存儲數據的容器,它的作用有點像數據庫的作用,而接口則提供了操作這些數據的方法。
下面來看下每個集合的底層數據結構是怎么實現的不廢話先上圖
在知道了集合的分類和底層實現后,在來看下最經常使用的幾個集合的源碼
1、ArrarList作為最經常使用的集合。
實現的后三個接口分別表示,該集合可以隨機訪問(通過下標訪問),克隆,序列化和反序列化(把對象轉換為字節序列的過程稱為對象的序列化。把字節序列恢復為對象的過程稱 為
對象的反序列化。)
實現的第一個接口List則表示ArrayList可以使用List接口的所有方法。
2.?類的成員屬性
public class ArrayList<E> extends AbstractList<E>implements List<E>, RandomAccess, Cloneable, java.io.Serializable {// 版本號private static final long serialVersionUID = 8683452581122892189L;// 缺省容量private static final int DEFAULT_CAPACITY = 10;// 空對象數組private static final Object[] EMPTY_ELEMENTDATA = {};// 缺省空對象數組private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};// 元素數組transient Object[] elementData;// 實際元素大小,默認為0private int size;// 最大數組容量private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; }說明:類的屬性中核心的屬性為elementData,類型為Object[],用于存放實際元素,并且被標記為transient,也就意味著在序列化的時候,此字段是不會被序列化的。
3.類的構造函數ArrayList(int)--初始化指定大小的集合
public ArrayList(int initialCapacity) {if (initialCapacity > 0) { // 初始容量大于0this.elementData = new Object[initialCapacity]; // 初始化元素數組} else if (initialCapacity == 0) { // 初始容量為0this.elementData = EMPTY_ELEMENTDATA; // 為空對象數組} else { // 初始容量小于0,拋出異常throw new IllegalArgumentException("Illegal Capacity: "+initialCapacity);}}說明:指定elementData數組的大小,不允許初始化大小小于0,否則拋出異常。
ArrayList()無參構造函數,當初始化時會給一個默認10的容量大小 /*** Constructs an empty list with an initial capacity of ten.*/public ArrayList() {this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;} ArrayList(Collection<? extends E> c) 參數為泛型的集合參數,即傳入的參數必須是集合的子類 /*** Constructs a list containing the elements of the specified* collection, in the order they are returned by the collection's* iterator.** @param c the collection whose elements are to be placed into this list* @throws NullPointerException if the specified collection is null*/public ArrayList(Collection<? extends E> c) {// 將傳入的集合轉為數組elementData = c.toArray();if ((size = elementData.length) != 0) {// c.toArray might (incorrectly) not return Object[] (see 6260652)
// 可能不返回object[]數組if (elementData.getClass() != Object[].class)
// 拷貝數據到object[]數組elementData = Arrays.copyOf(elementData, size, Object[].class);} else {// replace with empty array.this.elementData = EMPTY_ELEMENTDATA;}}
? 4.add方法
public boolean add(E e) {//對數組的容量進行調整ensureCapacityInternal(size + 1); // Increments modCount!!elementData[size++] = e;return true; }//在指定位置添加一個元素 public void add(int index, E element) {// 數組下標校驗rangeCheckForAdd(index);//對數組的容量進行調整ensureCapacityInternal(size + 1); // Increments modCount!!// 把index后的數據往后移一位,在index位置插入新元素System.arraycopy(elementData, index, elementData, index + 1,size - index);elementData[index] = element;size++; }//添加一個集合 public boolean addAll(Collection<? extends E> c) {//把該集合轉為對象數組Object[] a = c.toArray();int numNew = a.length;//增加容量ensureCapacityInternal(size + numNew); // Increments modCount//挨個向后遷移System.arraycopy(a, 0, elementData, size, numNew);size += numNew;//新數組有元素,就返回 truereturn numNew != 0; }//在指定位置,添加一個集合 public boolean addAll(int index, Collection<? extends E> c) {rangeCheckForAdd(index);Object[] a = c.toArray();int numNew = a.length;ensureCapacityInternal(size + numNew); // Increments modCountint numMoved = size - index;//原來的數組挨個向后遷移if (numMoved > 0)System.arraycopy(elementData, index, elementData, index + numNew,numMoved);//把新的集合數組 添加到指定位置System.arraycopy(a, 0, elementData, index, numNew);size += numNew;return numNew != 0; }
5.數組容量調整
public void ensureCapacity(int minCapacity) {int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)// 不是默認的數組,說明已經添加了元素? 0// 默認的容量 : DEFAULT_CAPACITY;if (minCapacity > minExpand) {//當前元素個數比默認容量大 ensureExplicitCapacity(minCapacity);} }private void ensureCapacityInternal(int minCapacity) {//還沒有添加元素if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {//最小容量取默認容量和 當前元素個數 最大值minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);}ensureExplicitCapacity(minCapacity); }private void ensureExplicitCapacity(int minCapacity) {modCount++;// 容量不夠了,需要擴容if (minCapacity - elementData.length > 0)grow(minCapacity); }6.擴容
private void grow(int minCapacity) {int oldCapacity = elementData.length;// 1.5 倍 原來容量int newCapacity = oldCapacity + (oldCapacity >> 1);//如果當前容量還沒達到 1.5 倍舊容量,就使用當前容量,省的站那么多地方if (newCapacity - minCapacity < 0)newCapacity = minCapacity;//新的容量居然超出了 MAX_ARRAY_SIZEif (newCapacity - MAX_ARRAY_SIZE > 0)//最大容量可以是 Integer.MAX_VALUEnewCapacity = hugeCapacity(minCapacity);// minCapacity 一般跟元素個數 size 很接近,所以新建的數組容量為 newCapacity 更寬松些elementData = Arrays.copyOf(elementData, newCapacity); }private static int hugeCapacity(int minCapacity) {if (minCapacity < 0) // overflowthrow new OutOfMemoryError();return (minCapacity > MAX_ARRAY_SIZE) ?Integer.MAX_VALUE :MAX_ARRAY_SIZE; }? ? ? ? ? ? ? ? ? ? ? ?
?7.查詢和修改
E elementData(int index) {return (E) elementData[index]; }//獲取 public E get(int index) {rangeCheck(index);//直接根據數組角標返回元素,快的一比return elementData(index); }//修改 public E set(int index, E element) {rangeCheck(index);E oldValue = elementData(index);//直接對數組操作elementData[index] = element;//返回原來的值return oldValue; }8、刪除
//根據位置刪除 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 workreturn oldValue; }//刪除某個元素 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; }//內部方法,“快速刪除”,就是把重復的代碼移到一個方法里 //沒看出來比其他 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 to let GC do its work }//保留公共的 public boolean retainAll(Collection<?> c) {Objects.requireNonNull(c);return batchRemove(c, true); }//刪除或者保留指定集合中的元素 private boolean batchRemove(Collection<?> c, boolean complement) {final Object[] elementData = this.elementData;//使用兩個變量,一個負責向后掃描,一個從 0 開始,等待覆蓋操作int r = 0, w = 0;boolean modified = false;try {//遍歷 ArrayList 集合for (; r < size; r++)//如果指定集合中是否有這個元素,根據 complement 判斷是否往前覆蓋刪除if (c.contains(elementData[r]) == complement)elementData[w++] = elementData[r];} finally {//發生了異常,直接把 r 后面的復制到 w 后面if (r != size) {System.arraycopy(elementData, r,elementData, w,size - r);w += size - r;}if (w != size) {// 清除多余的元素,clear to let GC do its workfor (int i = w; i < size; i++)elementData[i] = null;modCount += size - w;size = w;modified = true;}}return modified; }//清楚全部 public void clear() {modCount++;//并沒有直接使數組指向 null,而是逐個把元素置為空//下次使用時就不用重新 new 了for (int i = 0; i < size; i++)elementData[i] = null;size = 0; }9、indexof和lastindexof
public boolean contains(Object o) {return indexOf(o) >= 0; }//遍歷,第一次找到就返回 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 int lastIndexOf(Object o) {if (o == null) {for (int i = size-1; i >= 0; i--)if (elementData[i]==null)return i;} else {for (int i = size-1; i >= 0; i--)if (o.equals(elementData[i]))return i;}return -1; }由于 ArrayList 不是同步的,所以在并發訪問時,如果在迭代的同時有其他線程修改了 ArrayList, fail-fast 的迭代器 Iterator/ListIterator 會報 ConcurrentModificationException 錯。
因此我們在并發環境下需要外部給 ArrayList 加個同步鎖,或者直接在初始化時用 Collections.synchronizedList 方法進行包裝:
?
由于第一次寫總結博客,的確是中費時費力的工作,但也收獲頗多,如有不足還請輕噴。
參考博客:
https://blog.csdn.net/u011240877/article/details/52853989
https://blog.csdn.net/u011518120/article/details/52026076
https://www.cnblogs.com/leesf456/p/5308358.html
?
轉載于:https://www.cnblogs.com/angleshoot/p/10399945.html
總結
- 上一篇: day 17python 面对对象之继承
- 下一篇: Django与Ajax