【101】Java LinkedHashSet工作原理及实现



  • 1. 概述


    Hash table and linked list implementation of the Set interface, with predictable iteration order. This implementation differs from HashSet in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (insertion-order). Note that insertion order is not affected if an element is re-inserted into the set. (An element e is reinserted into a set s if s.add(e) is invoked when s.contains(e) would return true immediately prior to the invocation.)

    LinkedHashSet是基于HashMap和双向链表的实现。

    1. LinkedHashSet lset = new LinkedHashSet();
    2. lset.add(“语文”);
    3. lset.add(“数学”);
    4. lset.add(“英语”);
    5. lset.add(“历史”);
    6. lset.add(“政治”);
    7. lset.add(“地理”);
    8. lset.add(“生物”);
    9. lset.add(“化学”);
    10. for(String str : lset) {
    11. System.out.println(str);
    12. }

    利用链表来记录,保证了迭代输出的有序性。其具体结构如下所示:

    0_1470098597867_j1.png

    可以看出,其实现基本和LinkedHashMap一样。

    2. 关键实现


    1. public class LinkedHashSet
    2. extends HashSet
    3. implements Set, Cloneable, java.io.Serializable

    从继承关系来看就知道LinkedHashMap的实现非常简单,就是集成HashSet的接口,并且在构造时调用的是:

    1. HashSet(int initialCapacity, float loadFactor, boolean dummy) {
    2. map = new LinkedHashMap<>(initialCapacity, loadFactor);
    3. }

    因此,结构也便是如HashSet于HashMap一样,LinkedHashSet也便如LinkedHashMap一样,只是将Value做了一个dummy的object。

    参考资料


    LinkedHashSet
    最后附上@Yikun的博客,满满都是干货。http://yikun.github.io/about


登录后回复
 

与 BitTiger Community 的连接断开,我们正在尝试重连,请耐心等待