AbstractList<E>

AbstractList 继承了AbstractCollection,实现了List接口

public boolean add(E e) { 向list末尾追加一个元素
        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();
}以上三个需要根据下标操作集合元素的方法,都需要子类自己实现

迭代器内部类:
  使用一个游标记录位置,下一次next()返回的下标位置,使用lastRet记录最近调用的next()返回元素的位置,用于迭代器删除元素时
private class Itr implements Iterator<E> {
    int cursor = 0;
    int lastRet = -1;
    int expectedModCount = modCount; 记录List 的modCount值,后面每次调用next()的时候,都会检查迭代器期待的expectedModCount 和集合的modCount是否相等,如果不等,表示集合有并发修改,会抛出
    ConcurrentModificationException异常
  
public boolean hasNext() {
return cursor != size();
}

public E next() {
checkForComodification();
try {
int i = cursor;
E next = get(i);
lastRet = i;
cursor = i + 1;
return next;
} catch (IndexOutOfBoundsException e) {
checkForComodification();
throw new NoSuchElementException();
}
}

final void checkForComodification() {  // 检查是否有并发修改
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}

public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();

try {
AbstractList.this.remove(lastRet);
if (lastRet < cursor) // 移除元素后,将游标记录的位置-1
cursor--;
lastRet = -1;
expectedModCount = modCount; // 将expectedModCount重新赋值
} catch (IndexOutOfBoundsException e) {
throw new ConcurrentModificationException();
}
}
}



查找操作:
  public int indexOf():找到特定元素的下标,使用ListIterator从前往后找,找到第一次出现就返回。if the list doesnt contain the element,will return -1
  public int lastIndexOf():从后往前找特定元素的下标
批量操作:
  void clear(){
    removeRange(0,size()):清空所有元素
  }
  
 boolean addAll(int index, Collection c):

 

posted @ 2023-02-17 13:57  小小小小青石  阅读(28)  评论(0)    收藏  举报