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。

  • 相关阅读:
    开发一个delphi写的桌面图标管理代码
    web颜色转换为delphi
    delphi RGB与TColor的转换
    用Delphi制作仿每行带按钮的列表
    Delphi 之 编辑框控件(TEdit)
    numEdit
    DropDownList添加客户端下拉事件操作
    19个必须知道的Visual Studio快捷键
    asp.net线程批量导入数据时通过ajax获取执行状态
    详解JQuery Ajax 在asp.net中使用总结
  • 原文地址:https://www.cnblogs.com/zitai/p/13065036.html
Copyright © 2011-2022 走看看