首页 > 其他 > 详细

源码之HashSet

时间:2018-10-28 11:02:45      阅读:137      评论:0      收藏:0      [点我收藏+]
构造函数
    public HashSet() {
        map = new HashMap<>();
    }

    public HashSet(Collection<? extends E> c) {
        map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16));
        addAll(c);
    }

    public HashSet(int initialCapacity, float loadFactor) {
        map = new HashMap<>(initialCapacity, loadFactor);
    }

    public HashSet(int initialCapacity) {
        map = new HashMap<>(initialCapacity);
    }

   /**
     * 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);
    }

分析:
HashSet底层是HashMap实现的,你看最后一个构造函数就会很奇怪,这dummy的参数干啥的 ,啥也没用。不过这个看说明就知道了,只是为了实现构造函数的重载,跟其他区别开来的(如果不明白有必要看下重载内容)。

add方法

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

分析:
这就很简单可以知道了,就是将E作为HashMap的key,所有的key都指向PRESENT对象,因为我们都知道,key是不允许重复的,而value可以。

另外这里没有HashMap的那种get方法去获取key的,只能通过迭代器去便利里面的值。

总结:
1.它不是线程安全的
2.它是由HashMap实现的
3.通过map.put(key,PRESENT)方式把所有key指向同一个对象
4.访问只能通过迭代器访问。

源码之HashSet

原文:http://blog.51cto.com/4837471/2309838

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!