美文网首页
AbstractList抽象类

AbstractList抽象类

作者: 我姓杨却不是你信仰 | 来源:发表于2020-09-22 11:28 被阅读0次

AbstractList虽然是个抽象类,但是里面只有一个抽象方法。
要实现AbstractList里面的一些功能,子类必须覆盖AbstractList的方法。
官方文档说,用这个抽象类的意义就是简化了随机访问的一些代码,提高复用性。
add,remove等方法需要时覆盖重写,否则会抛出UnsupportedOperationException

public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {
/**
* Sole constructor. (For invocation by subclass constructors, typically
* implicit.)
*/
protected AbstractList() {
}

/**
 *  添加元素进列表的末尾,需覆盖重写
 */
public boolean add(E e) {
    add(size(), e);
    return true;
}

/**
 * 唯一的抽象类,若继承AbstractList,子类必须覆盖
 * 根据下标获取元素
 * 
 */
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();
}


// Search Operations <h2>搜索相关</h2> 

/**
 *  查找指定元素,第一次出现的索引值
 *  如果没有查找到,返回-1
 */
public int indexOf(Object o) {
    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;
}

/**
 * 查找指定元素,第一次出现的索引值
 * 如果没有查找到,返回-1
 */
public int lastIndexOf(Object o) {
    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;
}


// Bulk Operations

/**
 * 删除此列表中,所有元素
 */
public void clear() {
    removeRange(0, size());
}

/**
 * 将一个集合,插入到列表中的指定位置
 *
 */
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;
}


// Iterators
//AbstractList 中提供了两个迭代器的实现类,默认实现了迭代器接口,实现了对  
//元素的遍历,它们就是Itr 和其子类 ListItr,分别来了解一下。
//先看Itr类,Itr 实现了 Iterator 接口,重写了 next() 和 remove() 方法,

private class Itr implements Iterator<E> {
    /**
     * Index of element to be returned by subsequent call to next.
     */
    int cursor = 0;

    /**
     * Index of element returned by most recent call to next or
     * previous.  Reset to -1 if this element is deleted by a call
     * to remove.
     */
    //最近迭代的元素位置,每次使用完默认置为-1
    int lastRet = -1;

    //记录容器被修改的次数,值不相等说明有并发操作
    int expectedModCount = modCount;

    public boolean hasNext() {
        return cursor != size();
    }

    public E next() {
        //compare值是否相等,判断是否有并发
        checkForComodification();
        try {
            int i = cursor;
            E next = get(i);
            lastRet = i;
            cursor = i + 1;
            return next;
        } catch (IndexOutOfBoundsException e) {
            checkForComodification();
            throw new NoSuchElementException();
        }
    }

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

        try {
            AbstractList.this.remove(lastRet);
            if (lastRet < cursor)
                cursor--;
            lastRet = -1;
            expectedModCount = modCount;
        } catch (IndexOutOfBoundsException e) {
            throw new ConcurrentModificationException();
        }
    }

    final void checkForComodification() {
        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;
    }

    public E previous() {
        checkForComodification();
        try {
            int i = cursor - 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)
            throw new IllegalStateException();
        checkForComodification();

        try {
            AbstractList.this.set(lastRet, e);
            expectedModCount = modCount;
        } catch (IndexOutOfBoundsException ex) {
            throw new ConcurrentModificationException();
        }
    }

    public void add(E e) {
        checkForComodification();

        try {
            int i = cursor;
            AbstractList.this.add(i, e);
            lastRet = -1;
            cursor = i + 1;
            expectedModCount = modCount;
        } catch (IndexOutOfBoundsException ex) {
            throw new ConcurrentModificationException();
        }
    }
}

/**
 * subList就是切分集合,指定位置,返回切分后的列表
 *
 */
public List<E> subList(int fromIndex, int toIndex) {
    return (this instanceof RandomAccess ?
            new RandomAccessSubList<>(this, fromIndex, toIndex) :
            new SubList<>(this, fromIndex, toIndex));
}

// Comparison and hashing


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());
}

/**
 * 返回此列表的哈希码值。
 */
public int 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) {
    ListIterator<E> it = listIterator(fromIndex);
    for (int i=0, n=toIndex-fromIndex; i<n; i++) {
        it.next();
        it.remove();
    }
}

/**
 * 检查下标位置,是否数组越界
 */
protected transient int modCount = 0;

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();
}

}

相关文章

网友评论

      本文标题:AbstractList抽象类

      本文链接:https://www.haomeiwen.com/subject/hfovyktx.html