第一篇 Java集合总览

2018-01-12  本文已影响16人  顶级工程师闯天涯

Collection Framework 总览
官方的Collection

本文参考于:Collections in Java,刚兴趣的可以直接去看原文,不错的网站。

Collection Framework的历史渊源

在引入Collection Framework(即 JDK 1.2)之前,Java 处理多个对象的标准方法只有3种方法:
1.数组(array);
2.Vector;
3.Hashtable;
且三者之间没有公共的接口。
这样就造成在开发中,苦逼的程序猿不得不针对3种不同的实现来进行相应的操作。因为三者都有各自不同的方法和语法来处理成员。
给个栗子:

   public static void main(String[] args) {

        // create an instance of Array.
        int[] array = new int[]{1,2,3,4};
      
        // create an instance of Vector
        Vector<Integer> vector = new Vector<>(5);
        for (int i = 1; i < 5; i++) {
            vector.addElement(i);
        }
        // create an instance of Hashtable
        Hashtable<Integer,String> hashtable = new Hashtable<>(5);
        hashtable.put(1,"First");
        hashtable.put(2,"Second");
        hashtable.put(3,"Third");
        hashtable.put(4,"Fourth");
        // accessing first element of array,vector,hashtable.
  
        System.out.println("数组中的第一个元素:"+array[0]);
        System.out.println("Vector中的第一个元素:"+vector.elementAt(0));
        System.out.println("Hashtable中的第一个元素:"+hashtable.get(1));
         /**
         * 访问元素时,
         * Array 使用[], 
         * Vector 使用elementAt(), 
         * Hashtable 使用get().
         */
    }

从代码中我们可以发现,这三者(Array,Vector or Hashtable) 都没有实现一个标准的访问接口。所以编程人员难以对不同的集合写出通用的算法。另一个缺点是,Vector的很多方法都是final的,So我们没办法你通过继承Vector来实现相同的功能。

为了解决上述的问题,在JDK 1.2Java开发人员提出一个公共的接口并且引入了Collection Framework.并且修改了Vector 和 Hashtable来顺应这个Collection Framework.

JDK 1.2 引入了 Collection Framework.

Collection Framework的优势

集合框架的优势大致有以下三点:
1.稳健的API:这个API中包含一些接口,例如Collection, Set, List, and Map。其他的一些类(如ArrayList, LinkedList, Vector etc)都实现了这些接口,与此同时,这些接口中有一些公共的方法;
2.减轻编程负担:编程人员不必担心集合的设计,而可以在项目中集中精力地使用它;
3.提高程序的速度和质量:集合框架使用了高性能的数据结构和算法,从而提高了程序的性能;

Collection Framework的继承层次关系


             Collection                Map
         /     /    \      \            |
        /      /      \     \           |
     Set    List    Queue  Dequeue   SortedMap
     /
    /
 SortedSet 
            <strong>Core Interfaces in Collections</strong>
这里仅仅给出的是核心接口
  • Collection:顶层接口,它有基本的方法(add(),remove(),... etc.)
  • Set : 不允许元素重复(即不存在e1.equals(e2),最多只有一个null元素)。实现该接口有HashSet(基于HashCode)和TreeSet(基于平衡二叉树).值得注意的是,TreeSet implements SortedSet.
  • List:有序,且可以包含重复元素。其子类有(LinkedList and ArrayList ...)
  • Queue:遵守FIFO规则,当然也有一些例外(如 PriorityQueue...)
  • Deque:双端队列,允许在两端进行插入和删除。即可以FIFO and LIFO.
  • Map:键值对。键不允许重复。TreeMap implements SortedMap.
    Set 和 Map的区别在于,Set中只含有键,在Map中含有的是键值对。
具体的框架层次

欢迎查看下篇文章:详谈List

上一篇下一篇

猜你喜欢

热点阅读