黑马程序员技术交流社区

标题: 牛人跪求进来看下(关于AbstractList迭代问题) [打印本页]

作者: 編程浪子    时间: 2012-4-11 12:12
标题: 牛人跪求进来看下(关于AbstractList迭代问题)
public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {
   public E remove(int index) {//AbstractList方法
        throw new UnsupportedOperationException();
    }
private class Itr implements Iterator<E> {//内部类       
        int cursor = 0;
        int lastRet = -1;
        int expectedModCount = modCount;

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

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

        public void remove() {
            if (lastRet == -1)
                throw new IllegalStateException();
            checkForComodification();

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

        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }
    }
这是AbstractList抽象类里的一个源代码一部分,我想问一下Itr他这个内部类调用了remove方法,删除元素,但是AbstractList抽象类里的那个remove方法只是抛出一个异常,那它是怎么删除的呢??
作者: 刘士    时间: 2012-4-11 12:37
查API得知
  1. public abstract class AbstractList<E>extends AbstractCollection<E>implements List<E>此类提供 List 接口的骨干实现,以最大限度地减少实现“随机访问”数据存储(如数组)支持的该接口所需的工作。对于连续的访问数据(如链表),应优先使用 AbstractSequentialList,而不是此类。

  2. 要实现不可修改的列表,编程人员只需扩展此类,并提供 get(int) 和 size() 方法的实现。

  3. 要实现可修改的列表,编程人员必须另外重写 set(int, E) 方法(否则将抛出 UnsupportedOperationException)。如果列表为可变大小,则编程人员必须另外重写 add(int, E) 和 remove(int) 方法。
复制代码
根据我的理解为:在这里指的是继承AbstractList(或许并覆盖实现remove方法)的外部类。




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2