zoukankan      html  css  js  c++  java
  • Java数据结构一 —— Java Collections API中的表

    1.Collection接口

    位于java.util包中,以下是重要的部分。

    1  public interface Collection<AnyType> extends Iterable<AnyType> 
    2  { 
    3       int size();
    4       boolean isEmpty();
    5       void clear();
    6       boolean add(AnyType x);
    7       boolean remove(AnyType x);
    8       java.util.Iterator<AnyType> iterator();
    9  }

    Collection接口扩展了Iterable接口。实现Iterable接口的哪些类可以拥有增强的for循环,该循环施于这些类之上以观察它们所有的项。

    增强for循环示例:该print可以用来打印任意集合中的所有项。

    1 public static <AnyType> void print(Collection<AnyType> coll)
    2 {
    3     for(AnyType item : coll){
    4         System.out.println(item);
    5     }
    6 }

    2.Iterator接口:(个人认为这里迭代器就隐约有着C中指针的意味了)

      实现Iterable接口的结合必须提供一个称为iterator的方法,该方法返回一个Iterator类的对象。

    1 public interface Iterator<AnyType>
    2 {
    3     boolean hasNext();
    4     AnyType next();
    5     void remove();
    6 }
    View Code

    每次对next的调用都给出集合尚未见到的下一项。第一次调用给出第一项。

    编译器见到增强for循环会对其改写成使用迭代器的形式。如被编译器重写的print例子。

     public static <AnyType> void print(Collection<AnyType> coll)
     {
        Iteraror<AnyType> itr = coll.iterator();
        while(itr.hasNext()){
            AnyType item = itr.next();
            system.out.println(item);
        }     
    }
    View Code

    Iterator接口的remove方法和Collection接口的remove方法:

      Collection接口的remove方法:

        必须要找到被删除的项,涉及到开销问题。

      Iterator接口的remove方法:

        可以删除由next最新返回的项(即迭代器刚刚遍历过的项),此后我们不能再调用该remove方法,直到对next再一次调用后。

      当直接使用Iterator(而不是使用增强for循环)时,如果对正在被迭代的结合进行结构上的改变(即对该集合使用add、remove、clear方法),那么迭代器将不再合法抛出异常。但是如果迭代器调用了它自己的remove方法,那么仍旧是合法的。

    3.List接口

    java.util包中,继承Collection接口。以下仅列举重要的方法。

    public interface List<AnyType> extends Collection<AnyType>
    {
        AnyType get(int idx);
        AnyType set(int idx, AnyType newVal);
        void add(int idx, AnyType x);
        void remove(int idx);
        
        ListIterator<AnyType> listIterator(int poss);
    }
    View Code

    索引0位于表前段,size()-1代表表最后一项。List是一个接口,而List ADT有两种流行的实现方式:ArrayList(可增长数组实现)和LinkedList(双链表实现)。对于搜索而言,ArrayList和LinkedList都是低效的,均花费线性时间(二叉平衡搜索树则花费O(logN)时间)。

    ListIterator接口:

      扩展了Iterator的功能,添加了previous()和hasPrevious()。add()方法将一个新的项以当前位置放入表中。set()方法改变被迭代器看到的最后一个值。从而对LinkedList很方便。

    public interface ListIterator<AnyType> extends Iterator<AnyType>
    {
        boolean hasPrevious();
        AnyType previous();
        
        void add(AnyType x);
        void set(AnyType newVal)
    }
    View Code

     

  • 相关阅读:
    jQuery中 $ 符号的冲突问题
    典型用户,场景,用例图
    结对编程
    简易计算器
    对git的认识
    我的博客
    零基础免费搭建个人博客-hexo+github
    DTcmsV4.0分析学习——(3)URL重写
    DTcmsV4.0分析学习——(2)系统框架
    DTcmsV4.0分析学习——(1)数据库结构分析
  • 原文地址:https://www.cnblogs.com/LolaLiu/p/3976903.html
Copyright © 2011-2022 走看看