Java.util.AbstractList

本章關於抽象列列表做介紹

public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> //繼承了抽象集合並且實現List接口

抽象方法
abstract public E get(int index); 返回指定索引的元素

這裏寫代碼片

具體方法

public boolean add(E e) {  //添加一個元素
        add(size(), e);
        return true;
    }

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) { //返回o的索引,通過ListIterator遍歷集合
        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()))  //當運行it.next之後it已經向後走了,所以對應的索引是it 的前一個索引
                    return it.previousIndex();
        }
        return -1;
    }
//iterator往前遍歷,listIterator在Iterator的基礎上又增加了previous方法(因爲是線性,所以可以往前遍歷
public int lastIndexOf(Object o) {
        ListIterator<E> it = listIterator(size());  //初始化是多少則ListIterator對象的開始索引就在哪兒
        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());
    }
    //從index開始插入集合C中的元素
public boolean addAll(int index, Collection<? extends E> c) {
        rangeCheckForAdd(index);
        boolean modified = false;
        for (E e : c) {
            add(index++, e);
            modified = true;
        }
        return modified;
    }
//兩個集合相同必須每個元素都相同
public boolean equals(Object o) {
        if (o == this)
            return true;
        if (!(o instanceof 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());
    }
    //刪除範圍內的元素
protected void removeRange(int fromIndex, int toIndex) {
        ListIterator<E> it = listIterator(fromIndex);
        for (int i=0, n=toIndex-fromIndex; i<n; i++) {
            it.next();
            it.remove();
        }
    }


protected transient int modCount = 0; 集合被修改的次數

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章