LinkedHashSet

继承自 HashSet,不过比 HashSet 多的功能是它维护了一份双向链表,来将它所有的元素连接起来。遍历的顺序与插入的顺序是一致的。HashSet 不能保证这样的一致性。

看 LinkedHashSet 的源码,发现 LinkedHashSet 没有自己的方法,只有一些构造方法:

    public LinkedHashSet(int initialCapacity, float loadFactor) {
        super(initialCapacity, loadFactor, true);
    }

看对应的 HashSet 的代码:

/**
 * Constructs a new, empty linked hash set.  (This package private
 * constructor is only used by LinkedHashSet.) The backing
 * HashMap instance is a LinkedHashMap with the specified initial
 * capacity and the specified load factor.
 *
 * @param      initialCapacity   the initial capacity of the hash map
 * @param      loadFactor        the load factor of the hash map
 * @param      dummy             ignored (distinguishes this
 *             constructor from other int, float constructor.)
 * @throws     IllegalArgumentException if the initial capacity is less
 *             than zero, or if the load factor is nonpositive
 */
HashSet(int initialCapacity, float loadFactor, boolean dummy) {
    map = new LinkedHashMap<>(initialCapacity, loadFactor);
}

在这个构造方法中,dummy 的参数专门用来表示这个函数使用 LinkedHashMap,而不是 HashMap。一般我们自己使用 HashSet 的时候不会使用这个构造函数。所以可以这么理解:在HashSet 里面使用 LinkedHashMap 所谓底层实现,就是为了能够让 LinkedHashSet 可以直接继承 HashSet.

 

总结:

1. LinkedHashSet 继承自 HashSet。

2. HashSet 通常使用 HashMap 作为底层实现,而 LinkedHashSet 使用 LinkedHashMap 作为底层实现,就是为了使用双向链表来保证访问顺序与插入顺序一致。

 

参考链接:

1. https://docs.oracle.com/javase/8/docs/api/java/util/LinkedHashSet.html

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值