Java中的數(shù)據(jù)結(jié)構(gòu)(jdk8)

1. 總體來說

java中主要的集合接口有Collection、Map上煤。Collection有一個(gè)父接口藏斩,Collection有三個(gè)子接口List、Set菇存、Queue夸研。
數(shù)據(jù)結(jié)構(gòu)灰常重要,所以依鸥,從架構(gòu)體系到代碼需要深入理解亥至。另外,會(huì)盜一些圖贱迟,哈哈姐扮。


java集合框架.png

2.List 接口的實(shí)現(xiàn)——ArrayList

ArrayList 是我們最常用的java數(shù)據(jù)結(jié)構(gòu)之一,通過學(xué)習(xí)其源碼衣吠,主要掌握其實(shí)現(xiàn)原理茶敏、擴(kuò)容機(jī)制以及一些主要方法的使用與實(shí)現(xiàn)。最后自己動(dòng)手實(shí)現(xiàn)一個(gè)簡單的ArrayList蒸播。


ArrayList.png
2.1 基本了解ArrayList
  • ArrayList是基于數(shù)組實(shí)現(xiàn)的睡榆,是一個(gè)動(dòng)態(tài)數(shù)組萍肆,其容量能自動(dòng)增長,類似于C語言中的動(dòng)態(tài)申請內(nèi)存胀屿,動(dòng)態(tài)增長內(nèi)存塘揣。
  • ArrayList不是線程安全的,只能用在單線程環(huán)境下宿崭,多線程環(huán)境下可以考慮用Collections.synchronizedList(List l)函數(shù)返回一個(gè)線程安全的ArrayList類亲铡,也可以使用concurrent并發(fā)包下的CopyOnWriteArrayList類。
  • ArrayList實(shí)現(xiàn)了Serializable接口葡兑,因此它支持序列化奖蔓,能夠通過序列化傳輸,實(shí)現(xiàn)了RandomAccess接口讹堤,支持快速隨機(jī)訪問吆鹤,實(shí)際上就是通過下標(biāo)序號(hào)進(jìn)行快速訪問,實(shí)現(xiàn)了Cloneable接口洲守,能被克隆疑务。
  • 每個(gè)ArrayList實(shí)例都有一個(gè)容量,該容量是指用來存儲(chǔ)列表元素的數(shù)組的大小梗醇。它總是至少等于列表的大小知允。隨著向ArrayList中不斷添加元素,其容量也自動(dòng)增長叙谨。自動(dòng)增長會(huì)帶來數(shù)據(jù)向新數(shù)組的重新拷貝温鸽,因此,如果可預(yù)知數(shù)據(jù)量的多少手负,可在構(gòu)造ArrayList時(shí)指定其容量涤垫。在添加大量元素前,應(yīng)用程序也可以使用ensureCapacity操作來增加ArrayList實(shí)例的容量虫溜,這可以減少遞增式再分配的數(shù)量雹姊。
2.2 源碼閱讀理解
  • 屬性
//  默認(rèn)初始化容量為10
private static final int DEFAULT_CAPACITY = 10;
//一個(gè)空的對(duì)象數(shù)組用來存儲(chǔ)實(shí)例
private static final Object[] EMPTY_ELEMENTDATA = {};
//使用默認(rèn)構(gòu)造函數(shù)時(shí)
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
//當(dāng)前數(shù)據(jù)對(duì)象,用transient 修飾衡楞,不參與序列化
transient Object[] elementData; // non-private to simplify nested class access
//當(dāng)前數(shù)組長度吱雏,并非容量
private int size;
//數(shù)組的最大長度
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
  • 構(gòu)造方法

初始化帶容量的構(gòu)造器

/**
*初始化時(shí)帶容量如果大于0就new一個(gè)相應(yīng)大小的對(duì)象數(shù)組;容量等于
*0就調(diào)用預(yù)先定義好的空的對(duì)象數(shù)組瘾境;如果容量小于0則拋出 IllegalArgumentException
*/
public ArrayList(int initialCapacity) {
    if (initialCapacity > 0) {
        this.elementData = new Object[initialCapacity];
    } else if (initialCapacity == 0) {
        this.elementData = EMPTY_ELEMENTDATA;
    } else {
        throw new IllegalArgumentException("Illegal Capacity: "+
                                           initialCapacity);
    }
 }

默認(rèn)構(gòu)造器歧杏,容量是10

  public ArrayList() {
      this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
   }

帶Collention對(duì)象的構(gòu)造器

  1.把Collention對(duì)象轉(zhuǎn)換成數(shù)組并且賦值給elementData,把數(shù)組的大小賦值給size
  2.判斷是否為空數(shù)組如果是空數(shù)組則把預(yù)先聲明好的賦值給elementData;否則再做深拷貝
public ArrayList(Collection<? extends E> c) {
    elementData = c.toArray();
    if ((size = elementData.length) != 0) {
        // c.toArray might (incorrectly) not return Object[] (see 6260652)
        if (elementData.getClass() != Object[].class)
            elementData = Arrays.copyOf(elementData, size, Object[].class);
    } else {
          // replace with empty array.
          this.elementData = EMPTY_ELEMENTDATA;
      }
  }
  • 主要方法(先主后次)

add方法
有兩個(gè)迷守,add(E e)和add(int index, E element)

/**
 *1)確保數(shù)組已使用長度(size)加1之后足夠存下 下一個(gè)數(shù)據(jù)
 *2)修改次數(shù)modCount 標(biāo)識(shí)自增1犬绒,如果當(dāng)前數(shù)組已使用長度(size)加1后的大于當(dāng)前的數(shù)組長度,則調(diào)用grow方法兑凿,增長數(shù)組凯力,grow方法 
 *會(huì)將當(dāng)前數(shù)組的長度變?yōu)樵瓉砣萘康?.5倍茵瘾。
 *3)確保新增的數(shù)據(jù)有地方存儲(chǔ)之后,則將新元素添加到位于size的位置上咐鹤。
 *4)返回添加成功布爾值拗秘。
 */
public boolean add(E e) {
    ensureCapacityInternal(size + 1);  // Increments modCount!!
    elementData[size++] = e;
    return true;
}

private static int calculateCapacity(Object[] elementData, int minCapacity) {
    if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
        return Math.max(DEFAULT_CAPACITY, minCapacity);
    }
    return minCapacity;
}

private void ensureCapacityInternal(int minCapacity) {
    ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}

private void ensureExplicitCapacity(int minCapacity) {
    modCount++;

    // overflow-conscious code
    if (minCapacity - elementData.length > 0)
        grow(minCapacity);
}


/**
 * 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);
    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;
}


/**
 * 在指定的位置插入元素
 * list. Shifts the element currently at that position (if any) and
 * any subsequent elements to the right (adds one to their indices).
 *
 * @param index index at which the specified element is to be inserted
 * @param element element to be inserted
 * @throws IndexOutOfBoundsException {@inheritDoc}
 */
public void add(int index, E element) {
    //檢查插入位置是否越界,如果index>size或則index<0 拋出IndexOutOfBoundsException異常
    rangeCheckForAdd(index);

    ensureCapacityInternal(size + 1);  // Increments modCount!!
    System.arraycopy(elementData, index, elementData, index + 1,
                     size - index);
    elementData[index] = element;
    size++;
}

remove方法
一共涉及到四個(gè)方法分別是祈惶,E remove(int index) 雕旨、boolean remove(Object o)、 fastRemove(int index)捧请、clear() 凡涩。

/**
 * 移除指定位置的元素
 * Shifts any subsequent elements to the left (subtracts one from their
 * indices).
 *
 * @param index the index of the element to be removed
 * @return the element that was removed from the list
 * @throws IndexOutOfBoundsException {@inheritDoc}
 */
public E remove(int index) {
    //邊界檢查
    rangeCheck(index);

    modCount++;
    //需要移除的數(shù)據(jù)
    E oldValue = elementData(index);
    //計(jì)算需要移動(dòng)的數(shù)量
    int numMoved = size - index - 1;
    if (numMoved > 0)
        System.arraycopy(elementData, index+1, elementData, index,
                         numMoved);
     //移除了一個(gè)元素,index后的元素都向前移動(dòng)了一位疹蛉,最后一個(gè)元素被孤立活箕,需要被GC回收,這點(diǎn)effective java  中也有說明
    elementData[--size] = null; // clear to let GC do its work
    return oldValue;
}

/**
 * 遍歷元素氧吐,通過匹配值讹蘑,刪除指定的對(duì)象
 * if it is present.  If the list does not contain the element, it is
 * unchanged.  More formally, removes the element with the lowest index
 * <tt>i</tt> such that
 * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>
 * (if such an element exists).  Returns <tt>true</tt> if this list
 * contained the specified element (or equivalently, if this list
 * changed as a result of the call).
 *
 * @param o element to be removed from this list, if present
 * @return <tt>true</tt> if this list contained the specified element
 */
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;
}

/*
 * 實(shí)現(xiàn)快熟刪除末盔,原理是向前移動(dòng)數(shù)組筑舅,再把最后一個(gè)元素置空,讓GC回收
 * return the value removed.
 */
private void fastRemove(int index) {

    modCount++;
    //需要移動(dòng)的元素個(gè)數(shù)
    int numMoved = size - index - 1;
    if (numMoved > 0)
  //把index后的元素向前復(fù)制移動(dòng)           System.arraycopy(elementData, index+1, elementData, index,
                         numMoved);
    elementData[--size] = null; // clear to let GC do its work
}

/**
 * 清空list陨舱,遍歷數(shù)組把每個(gè)元素置空翠拣,讓GC能夠回收
 * be empty after this call returns.
 */
public void clear() {
    modCount++;

    // clear to let GC do its work
    for (int i = 0; i < size; i++)
        elementData[i] = null;

    size = 0;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市游盲,隨后出現(xiàn)的幾起案子误墓,更是在濱河造成了極大的恐慌,老刑警劉巖益缎,帶你破解...
    沈念sama閱讀 218,755評(píng)論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件谜慌,死亡現(xiàn)場離奇詭異,居然都是意外死亡莺奔,警方通過查閱死者的電腦和手機(jī)欣范,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,305評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來令哟,“玉大人恼琼,你說我怎么就攤上這事∑粮唬” “怎么了晴竞?”我有些...
    開封第一講書人閱讀 165,138評(píng)論 0 355
  • 文/不壞的土叔 我叫張陵,是天一觀的道長狠半。 經(jīng)常有香客問我噩死,道長颤难,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,791評(píng)論 1 295
  • 正文 為了忘掉前任已维,我火速辦了婚禮乐严,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘衣摩。我一直安慰自己昂验,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,794評(píng)論 6 392
  • 文/花漫 我一把揭開白布艾扮。 她就那樣靜靜地躺著既琴,像睡著了一般。 火紅的嫁衣襯著肌膚如雪泡嘴。 梳的紋絲不亂的頭發(fā)上甫恩,一...
    開封第一講書人閱讀 51,631評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音酌予,去河邊找鬼磺箕。 笑死,一個(gè)胖子當(dāng)著我的面吹牛抛虫,可吹牛的內(nèi)容都是我干的松靡。 我是一名探鬼主播,決...
    沈念sama閱讀 40,362評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼建椰,長吁一口氣:“原來是場噩夢啊……” “哼雕欺!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起棉姐,我...
    開封第一講書人閱讀 39,264評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤屠列,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后伞矩,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體笛洛,經(jīng)...
    沈念sama閱讀 45,724評(píng)論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,900評(píng)論 3 336
  • 正文 我和宋清朗相戀三年乃坤,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了苛让。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,040評(píng)論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡侥袜,死狀恐怖蝌诡,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情枫吧,我是刑警寧澤浦旱,帶...
    沈念sama閱讀 35,742評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站九杂,受9級(jí)特大地震影響颁湖,放射性物質(zhì)發(fā)生泄漏宣蠕。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,364評(píng)論 3 330
  • 文/蒙蒙 一甥捺、第九天 我趴在偏房一處隱蔽的房頂上張望抢蚀。 院中可真熱鬧,春花似錦镰禾、人聲如沸皿曲。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,944評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽屋休。三九已至,卻和暖如春备韧,著一層夾襖步出監(jiān)牢的瞬間劫樟,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,060評(píng)論 1 270
  • 我被黑心中介騙來泰國打工织堂, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留叠艳,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,247評(píng)論 3 371
  • 正文 我出身青樓易阳,卻偏偏與公主長得像附较,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子闽烙,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,979評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容