zoukankan      html  css  js  c++  java
  • AbstractSequentialList源码分析

    该类与AbstractList类是另外一套抽象类,前者是在迭代器的基础上实现的get、set、add和remove方法,后者则是随机访问基础上实现这些方法。


    源码分析(JDK1.8)

    //构造方法
    protected AbstractSequentialList() {
    }
    
    //根据索引获取元素(通过迭代器寻找元素)
    public E get(int index) {
      try {
        return listIterator(index).next();
      } catch (NoSuchElementException exc) {
        throw new IndexOutOfBoundsException("Index: "+index);
      }
    }
    
    //根据索引更新元素(通过迭代器寻找元素)
    public E set(int index, E element) {
      try {
        ListIterator<E> e = listIterator(index);
        E oldVal = e.next();
        e.set(element);
        return oldVal;
      } catch (NoSuchElementException exc) {
        throw new IndexOutOfBoundsException("Index: "+index);
      }
    }
    
    //根据索引添加元素(通过迭代器寻找元素)
    public void add(int index, E element) {
      try {
        listIterator(index).add(element);
      } catch (NoSuchElementException exc) {
        throw new IndexOutOfBoundsException("Index: "+index);
      }
    }
    
    //根据索引删除迭代器(通过迭代器寻找元素)
    public E remove(int index) {
      try {
        ListIterator<E> e = listIterator(index);
        E outCast = e.next();
        e.remove();
        return outCast;
      } catch (NoSuchElementException exc) {
        throw new IndexOutOfBoundsException("Index: "+index);
      }
    }
    
    //在索引位置后添加其他容器数据
    public boolean addAll(int index, Collection<? extends E> c) {
      try {
        boolean modified = false;
        ListIterator<E> e1 = listIterator(index);
        Iterator<? extends E> e2 = c.iterator();
        while (e2.hasNext()) {
          e1.add(e2.next());
          modified = true;
        }
        return modified;
      } catch (NoSuchElementException exc) {
        throw new IndexOutOfBoundsException("Index: "+index);
      }
    }
    
    //获取迭代器
    public Iterator<E> iterator() {
      return listIterator();
    }
    
    //抽象类,获取next为index的迭代器
    public abstract ListIterator<E> listIterator(int index);
    
    

    总结:

    通过代码可以知道,几乎所有方法都依靠 listIterator(int index)抽象方法 来实现,功能都是依靠迭代器,不支持快速随机访问,及不支持RandomAccess。

  • 相关阅读:
    博客搬迁
    Android 集成FaceBook实现第三方登陆
    android-Xfermode模式详解
    android FileNotFoundException
    EditText 隐藏或者显示输入内容
    Fragment+ViewPager静止滑动,去掉默认的滑动效果
    Xcode 常用插件(持久更新)
    XMPP- JID 与 XMPP的命名空间
    android openfire 和 xmpp
    IOS-数据持久化的几种方式
  • 原文地址:https://www.cnblogs.com/zitai/p/13065036.html
Copyright © 2011-2022 走看看