Map,List,Set,Queue小结

来源:互联网 发布:华为手机删除数据 编辑:程序博客网 时间:2024/06/16 04:32
  • 一、继承结构

  • |-Iterator(interface)

    |-Collection(interface)    |-List(interface) 【有序,可重复集合,可以有null】        |-ArrayList  【非线程安全,适合查、改;初始容量为10 】        |-LinkedList 【非线程安全,适合增、删】        |-Vector 【线程安全,适合查、改】            |-Stack【比Vector多5个方法】    |-Set(interface) 【不可重复集合 】        |-HashSet 【无序】            |-LinkedHashSet 【有序,默认按插入的顺序】        |-SortedSet(interface)            |-TreeSet 【有序,默认按key升序】    |-Queue(interface)        |-PriorityQueue        |-LinkedList
  • |-Map(interface)【由多个key-value对组成的集合,Map 集合的key 具有一个特征:所有key 不能重复,key 之间没有顺序】

        |-HashTable    |-HashMap【初始容量16,无序,可以为null】        |-LinkedHashMap【有序,按插入的顺序】    |-SortedMap(interface)         |-TreeMap 【有序,默认按key升序,不可以为null】
  • 二、集合框架关系详图

这里写图片描述

三、实现类比较

  • 3.1 Vector和ArrayList比较
    Vector 和ArrayList 这两个集合类的本质并没有太大的不同,它们都实现了List 接口,而且底层都是基于Java 数组来存储集合元素。
    在ArrayList 集合类的源代码中可以看到如下一行。
    private transient Object[] elementData;
    在Vector 集合类的源代码中也可看到类似的一行。
    protected Object[] elementData;
    从上面代码可以看出,ArrayList 使用transient 修饰了elementData 数组。这保证系统序列化ArrayList 对象时不会直接序列化elementData 数组,而是通过 ArrayList 提供的writeObject、readObject 方法来实现定制序列化;但对于Vector 而言,它没有使用transient 修饰elementData数组,而且Vector 只提供了一个writeObject 方法,并未完全实现定制序列化。
    从序列化机制的角度来看,ArrayList 的实现比Vector 的实现更安全。
    除此之外,Vector 其实就是ArrayList 的线程安全版本,ArrayList 和Vector 绝大部分方法的实现都是相同的,只是Vector 的方法增加了synchronized 修饰。
    ArrayList 总是将底层数组容量扩充为原来的1.5 倍,但Vector 则多了一个选择:当capacityIncrement 实例变量大于0 时,扩充后的容量等于原来的容量加上
    capacityIncrement 的值。Vector 的ensureCapacityHelper(int minCapacity)方法在扩充底层数组容量时多一个选择是因为,创建Vector 可以传入一个capacityIncrement参数。
  • 3.2 ArrayList和LinkedList比较
    1)ArrayList 和Vector是采用动态数组方式存储数据,LinkedList使用双向链表实现存储。
    2)ArrayList索引数据快,插入数据慢。LinkedList按序号索引数据需要移动指针,向前或向后遍历,所以索引指定位置元素慢;插入数据只需要记录元素的前后项即可,所以插入数度快。
    大部分情况下,ArrayList 的性能总是优于LinkedList,因此绝大部分都应该考虑使用ArrayList 集合。但如果程序经常需要添加、删除元素,尤其是经常需要调用add(E e)方法向集合中添加元素时,则应该考虑使用LinkedList集合。
  • 3.3 HashMap,LinkedHashMap,TreeMap比较
    HashMap无序,LinkedHashMap、TreeMap有序,LinkedHashMap通过private transient Entry header;来记录元素插入的顺序或者是元素被访问的顺序;TreeMap通过红黑树进行确定顺序。
0 0