Java集合之AbstractList抽象類別__java

來源:互聯網
上載者:User
//此類提供 List 介面的骨幹實現,以最大限度地減少實現"隨機訪問"資料存放區(如數組)支援的該介面所需的工作。//對於連續的訪問資料(如鏈表),應優先使用 AbstractSequentialList,而不是此類               jdk1.7    java.utilpublic abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {    protected AbstractList() {    }    public boolean add(E e) {    //將指定的元素添加到此列表的尾部        add(size(), e);        return true;    }    abstract public E get(int index);//返回列表中指定位置的元素    public E set(int index, E element) {//用指定元素其他清單中指定位置的元素,直接拋出異常        throw new UnsupportedOperationException();    }    public void add(int index, E element) {//在列表的指定位置插入指定元素,直接拋出異常        throw new UnsupportedOperationException();    }    public E remove(int index) {//移除列表中指定位置的元素,直接拋出異常        throw new UnsupportedOperationException();    }    public int indexOf(Object o) {//返回此列表中第一次出現的指定元素的索引,不包含此元素則返回-1        ListIterator<E> it = listIterator();//擷取內部實現的雙向迭代器        if (o==null) {            while (it.hasNext())                if (it.next()==null)                    return it.previousIndex();        } else {            while (it.hasNext())                if (o.equals(it.next()))                    return it.previousIndex();        }        return -1;    }    public int lastIndexOf(Object o) {//返回此列表中最後一次出現的指定元素的索引,不包含此元素則返回-1        ListIterator<E> it = listIterator(size());//擷取內部實現的雙向迭代器        if (o==null) {            while (it.hasPrevious())                if (it.previous()==null)                    return it.nextIndex();        } else {            while (it.hasPrevious())                if (o.equals(it.previous()))                    return it.nextIndex();        }        return -1;    }    public void clear() {//清空        removeRange(0, size());    }    public boolean addAll(int index, Collection<? extends E> c) {//將指定 collection 中的所有元素都插入到列表中的指定位置        rangeCheckForAdd(index);//參數有效性檢查        boolean modified = false;        for (E e : c) {            add(index++, e);            modified = true;        }        return modified;//成功則返回true    }    public Iterator<E> iterator() {//擷取該list的迭代器        return new Itr();    }    public ListIterator<E> listIterator() {//擷取該list的雙向迭代器        return listIterator(0);    }    //返回列表中元素的列表迭代器(按適當順序),從列表的指定位置開始。指定的索引表示 next的初始調用所返回的第一個元素    public ListIterator<E> listIterator(final int index) {        rangeCheckForAdd(index);//參數有效性檢查        return new ListItr(index);    }    protected transient int modCount = 0;//實際修改次數 。transient表示不進行序列化        private class Itr implements Iterator<E> {//內部迭代器的實現,繼承Iterator介面        int cursor = 0;//遊標,下一個要訪問的元素的索引        int lastRet = -1;//表示上一個訪問的元素的索引        int expectedModCount = modCount;//表示對ArrayList修改次數的期望值,它的初始值為modCount(表示實際修改次數),初始值為0        public boolean hasNext() {//是否有元素可以迭代            return cursor != size();//當遊標不等於個數時返回true        }        public E next() {//next方法        //判斷expectedModCount是否等於modCount,當調用迭代器時,又使用了集合裡的add或者remove方法就報錯,應使用迭代器裡的remove方法            checkForComodification();            try {                int i = cursor;                E next = get(i);//擷取當前值                lastRet = i;//更新lastRet                cursor = i + 1;//儲存下一次要迭代的元素的索引                return next;            } catch (IndexOutOfBoundsException e) {                checkForComodification();                throw new NoSuchElementException();            }        }        public void remove() {//移除            if (lastRet < 0)                throw new IllegalStateException();            //判斷expectedModCount(期望修改次數)是否等於modCount(實際修改次數),不等則拋出異常            checkForComodification();//            try {            //調用外部類的remove方法,會對modCount加1,並且lastRet初始值為-1,必須調用next方法後才能調用該remove方法                AbstractList.this.remove(lastRet);                if (lastRet < cursor)                    cursor--;//讓cursor減1,保證刪除元素後的下一次迭代是正確的元素                lastRet = -1;//給lastRet重新賦值                expectedModCount = modCount;//上面加1了,所以此處需要重新賦值            } catch (IndexOutOfBoundsException e) {                throw new ConcurrentModificationException();            }        }        final void checkForComodification() {//校正expectedModCount(期望修改次數)是否等於modCount(實際修改次數)            if (modCount != expectedModCount)                throw new ConcurrentModificationException();        }    }    //實現雙向迭代器介面    private class ListItr extends Itr implements ListIterator<E> {        ListItr(int index) {            cursor = index;//構造器,開始迭代的地方        }        public boolean hasPrevious() {            return cursor != 0;//索引為0時,就沒有前一個元素了        }        public E previous() {//反向迭代            checkForComodification();//校正expectedModCount(期望修改次數)是否等於modCount(實際修改次數),原理同前面            try {                int i = cursor - 1;//索引-1                E previous = get(i);//擷取元素                lastRet = cursor = i;//重新賦值                return previous;            } catch (IndexOutOfBoundsException e) {                checkForComodification();                throw new NoSuchElementException();            }        }        public int nextIndex() {//下一個索引            return cursor;        }        public int previousIndex() {//前一個索引            return cursor-1;        }        public void set(E e) {            if (lastRet < 0)//設定點的索引小於0拋出異常                throw new IllegalStateException();//            checkForComodification();//校正expectedModCount(期望修改次數)是否等於modCount(實際修改次數),原理同前面            try {                AbstractList.this.set(lastRet, e);//調用外部類的set進行修改,會讓modCount加1,所以需要重新賦值                expectedModCount = modCount;            } catch (IndexOutOfBoundsException ex) {                throw new ConcurrentModificationException();            }        }        public void add(E e) {//在迭代的位置增加            checkForComodification();//校正expectedModCount(期望修改次數)是否等於modCount(實際修改次數),原理同前面            try {                int i = cursor;                AbstractList.this.add(i, e);//調用外部類的add進行修改,會讓modCount加1,所以需要重新賦值                lastRet = -1;//每次增加之後lastRet賦值為-1,所以不能即刻進行刪除,需重新調用next方法                cursor = i + 1;                expectedModCount = modCount;            } catch (IndexOutOfBoundsException ex) {                throw new ConcurrentModificationException();            }        }    }    public boolean equals(Object o) {        if (o == this)//引用相等則必然相等            return true;        if (!(o instanceof List))//是否是list類型或其子類型            return false;        ListIterator<E> e1 = listIterator();        ListIterator e2 = ((List) o).listIterator();        while (e1.hasNext() && e2.hasNext()) {            E o1 = e1.next();            Object o2 = e2.next();            if (!(o1==null ? o2==null : o1.equals(o2)))//每一個元素相等                return false;        }        return !(e1.hasNext() || e2.hasNext());//如果元素個數不等則不相等    }    public int hashCode() {//hashCode計算        int hashCode = 1;        for (E e : this)            hashCode = 31*hashCode + (e==null ? 0 : e.hashCode());        return hashCode;    }    protected void removeRange(int fromIndex, int toIndex) {//移除集合中從fromIndex(包括)到toIndex(不包括)直接的元素        ListIterator<E> it = listIterator(fromIndex);//從當前位置開始迭代        for (int i=0, n=toIndex-fromIndex; i<n; i++) {            it.next();            it.remove();        }    }    private void rangeCheckForAdd(int index) {//參數範圍檢查        if (index < 0 || index > size())            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));    }    private String outOfBoundsMsg(int index) {//封裝異常資訊        return "Index: "+index+", Size: "+size();    }}//擷取集合中從fromIndex(包括)到toIndex(不包括)元素組成新的集合,是淺複製,引用會互相影響public List<E> subList(int fromIndex, int toIndex) {//RandomAccess介面是List實現所使用的標記介面,用來表明其支援快速(通常是固定時間)隨機訪問//在對List特別的遍曆演算法中,要盡量來判斷是屬於RandomAccess(如ArrayList)還是SequenceAccess(如LinkedList)//因為適合RandomAccess List的遍曆演算法,用在SequenceAccess List上就差別很大    return (this instanceof RandomAccess ?   //只有ArrayList實現了RandomAccess介面,判斷是否是ArrayList或其子類            new RandomAccessSubList<>(this, fromIndex, toIndex) :            new SubList<>(this, fromIndex, toIndex));}class SubList<E> extends AbstractList<E> {    private final AbstractList<E> l;//l僅僅是直接複製了原list的引用,所以對l的訪問會直接存取外部類,通過不同的索引來訪問不同的元素    private final int offset;//位移量    private int size;//大小    SubList(AbstractList<E> list, int fromIndex, int toIndex) {        if (fromIndex < 0)            throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);        if (toIndex > list.size())            throw new IndexOutOfBoundsException("toIndex = " + toIndex);        if (fromIndex > toIndex)            throw new IllegalArgumentException("fromIndex(" + fromIndex +                                               ") > toIndex(" + toIndex + ")");        l = list;//複製原list引用        offset = fromIndex;//位移量        size = toIndex - fromIndex;//大小        //this.modCount訪問自身的modCount;l.modCount訪問外部類的modCount(l是指向外部類的一個引用,直接複製引用過來的)        this.modCount = l.modCount;    }    public E set(int index, E element) {//修改元素        rangeCheck(index);//參數校正        //判斷this.modCount是否等於l.modCount,如果用SubList的同時對外部類集合進行修改(會影響到modCount的方法),拋出異常        checkForComodification();        return l.set(index+offset, element);    }    public E get(int index) {//擷取元素        rangeCheck(index);//參數校正      //判斷this.modCount是否等於l.modCount,如果用SubList的同時對外部類集合進行修改(會影響到modCount的方法),拋出異常        checkForComodification();        return l.get(index+offset);    }    public int size() {//大小    //判斷this.modCount是否等於l.modCount,如果用SubList的同時對外部類集合進行修改(會影響到modCount的方法),拋出異常        checkForComodification();        return size;    }    public void add(int index, E element) {//新增元素        rangeCheckForAdd(index);      //判斷this.modCount是否等於l.modCount,如果用SubList的同時對外部類集合進行修改(會影響到modCount的方法),拋出異常        checkForComodification();        l.add(index+offset, element);        this.modCount = l.modCount;        size++;    }    public E remove(int index) {//移除元素        rangeCheck(index);      //判斷this.modCount是否等於l.modCount,如果用SubList的同時對外部類集合進行修改(會影響到modCount的方法),拋出異常        checkForComodification();        E result = l.remove(index+offset);        this.modCount = l.modCount;        size--;        return result;    }    protected void removeRange(int fromIndex, int toIndex) {//移除fromIndex(包括)到toIndex(不包括)的範圍內元素    //判斷this.modCount是否等於l.modCount,如果用SubList的同時對外部類集合進行修改(會影響到modCount的方法),拋出異常        checkForComodification();        l.removeRange(fromIndex+offset, toIndex+offset);        this.modCount = l.modCount;        size -= (toIndex-fromIndex);    }    public boolean addAll(Collection<? extends E> c) {//增加集合內的元素        return addAll(size, c);    }    public boolean addAll(int index, Collection<? extends E> c) {//從index處開始增加集合內的元素        rangeCheckForAdd(index);        int cSize = c.size();        if (cSize==0)            return false;        checkForComodification();        l.addAll(offset+index, c);        this.modCount = l.modCount;        size += cSize;        return true;    }    public Iterator<E> iterator() {//返回迭代器        return listIterator();    }    public ListIterator<E> listIterator(final int index) {//迭代器的實現,同前面        checkForComodification();        rangeCheckForAdd(index);        return new ListIterator<E>() {            private final ListIterator<E> i = l.listIterator(index+offset);            public boolean hasNext() {                return nextIndex() < size;            }            public E next() {                if (hasNext())                    return i.next();                else                    throw new NoSuchElementException();            }            public boolean hasPrevious() {                return previousIndex() >= 0;            }            public E previous() {                if (hasPrevious())                    return i.previous();                else                    throw new NoSuchElementException();            }            public int nextIndex() {                return i.nextIndex() - offset;            }            public int previousIndex() {                return i.previousIndex() - offset;            }            public void remove() {                i.remove();                SubList.this.modCount = l.modCount;                size--;            }            public void set(E e) {                i.set(e);            }            public void add(E e) {                i.add(e);                SubList.this.modCount = l.modCount;                size++;            }        };    }    public List<E> subList(int fromIndex, int toIndex) {//構建新的list,淺複製        return new SubList<>(this, fromIndex, toIndex);    }    private void rangeCheck(int index) {//參數校正        if (index < 0 || index >= size)            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));    }    private void rangeCheckForAdd(int index) {//參數校正        if (index < 0 || index > size)            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));    }    private String outOfBoundsMsg(int index) {//異常資訊封裝        return "Index: "+index+", Size: "+size;    }  //判斷this.modCount是否等於l.modCount,如果用SubList的同時對外部類集合進行修改(會影響到modCount的方法),拋出異常    private void checkForComodification() {        if (this.modCount != l.modCount)            throw new ConcurrentModificationException();    }}//實現了RandomAccess介面,標記介面(Marker),它沒有任何方法。如果List子類實現了RandomAccess介面,那就表示它能夠快速隨機訪問儲存的元素。class RandomAccessSubList<E> extends SubList<E> implements RandomAccess {    RandomAccessSubList(AbstractList<E> list, int fromIndex, int toIndex) {        super(list, fromIndex, toIndex);    }    public List<E> subList(int fromIndex, int toIndex) {//構建新的list        return new RandomAccessSubList<>(this, fromIndex, toIndex);    }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.