HashSet/TreeSet异同点

 

很多人都知道HashMap, ConcurrentHashMap.但是可能对HashSet 和TreeSet 了解不多。

 

1. HashSet 是一个去重复的set集合

  内部实现,其实很简单就是包装了一下HashMap, 主要使用到key, Value是固定的 private static final Object PRESENT = new Object();

看看基础定义:

 
    static final long serialVersionUID = -5024744406713321676L;

    private transient HashMap<E,Object> map;

    // Dummy value to associate with an Object in the backing Map
    private static final Object PRESENT = new Object();

    /**
     * Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
     * default initial capacity (16) and load factor (0.75).
     */
    public HashSet() {
        map = new HashMap<>();
    }

 再来看看add方法, 实际操作是往map里面put key和一个常量, 如果不存在那么hashMap返回值没null,

    public boolean add(E e) {
        return map.put(e, PRESENT)==null;
    }

同理还是有remove 方法

  public boolean remove(Object o) {
        return map.remove(o)==PRESENT;
    }

相信通过上面说明,对HashSet的底层实现应该有所了解

2.TreeMap 是一个有序的Map, 很容易想到,对Key进行了排序。

看看treeMap的基础属性定义, 关键因素就是看看private transient Entry<K,V> root到底是什么了。

 /**
     * The comparator used to maintain order in this tree map, or
     * null if it uses the natural ordering of its keys.
     *
     * @serial, 这个很容易想到是用来排序的
     */
    private final Comparator<? super K> comparator;

  // 这个是存储具体对象的数据结构
    private transient Entry<K,V> root;

    /**
     * The number of entries in the tree
     */
    private transient int size = 0;

    /**
     * The number of structural modifications to the tree.
     */
    private transient int modCount = 0;

看到这个属性定义,可以知道,TreeMap 是一颗红黑树的实现。 红黑树是一个不完全的有序的二叉树。

 static final class Entry<K,V> implements Map.Entry<K,V> {
        K key;
        V value;
        Entry<K,V> left;
        Entry<K,V> right;
        Entry<K,V> parent;
        boolean color = BLACK;

        /**
         * Make a new cell with given key, value, and parent, and with
         * {@code null} child links, and BLACK color.
         */
        Entry(K key, V value, Entry<K,V> parent) {
            this.key = key;
            this.value = value;
            this.parent = parent;
        }

 

通过上面2个代码的查看,总结如下:

HashSet 内部是用来Hashmap的key作为set集合

TreeMap 内部使用了红黑树来实现有序。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值