zoukankan      html  css  js  c++  java
  • Core Java 简单谈谈HashSet

      同学们在看这个问题的时候,我先提出者两个问题,然后大家带着问题看这个文章会理解的更好。

    1. HashSet为什么添加元素时不能添加重复元素?
    2. HashSet是否添加null元素?

      打开源码, 我们看到如下代码,我们看到HashSet也有一个HashMap做为属性,HashSet()的构造方法就是将这个map实例化。如果大家对HashMap还不了解话,可以看我的这篇博文。还要注意有一个静态final的对象PRESENT,这个是干什么用的,咱们继续往下看。

        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方法,其就是将元素e放到HashMap中,然后将静态final对象PRESENT作为value放到里边,如果添加成功,那么HashMap返回null,然后也就是添加成功了,上一篇博文也讲到了,咱们再讲一次作为复习。如果将element放到HashMap里边,首先判断其hashCode,如果hashCode没有找到,就根据hashCode计算index放到对应的bucket中,如果hashCode相同的话,那么再根据key的是否equals作为第二判断,放到相应的linked list里边了。

        /**
         * Adds the specified element to this set if it is not already present.
         * More formally, adds the specified element <tt>e</tt> to this set if
         * this set contains no element <tt>e2</tt> such that
         * <tt>(e==null&nbsp;?&nbsp;e2==null&nbsp;:&nbsp;e.equals(e2))</tt>.
         * If this set already contains the element, the call leaves the set
         * unchanged and returns <tt>false</tt>.
         *
         * @param e element to be added to this set
         * @return <tt>true</tt> if this set did not already contain the specified
         * element
         */
        public boolean add(E e) {
            return map.put(e, PRESENT)==null;
        

      当然第二个问题同学们是否也想到了,因为hashMap是支持key为null的,所以HashSet也是可以添加key为null的元素的。HashMap用的地方这么多,大家知道它很重要了吧?!

  • 相关阅读:
    Codeforces 897 B.Chtholly's request-思维题(处理前一半)
    Codeforces 897 A.Scarborough Fair-字符替换
    51nod 1649.齐头并进-最短路(Dijkstra)
    牛客网 牛客练习赛7 B.购物-STL(priority_queue)
    牛客网 牛客练习赛7 A.骰子的游戏
    hdu 4737 A Bit Fun 尺取法
    Educational Codeforces Round 15 D. Road to Post Office 数学
    Educational Codeforces Round 15 A, B , C 暴力 , map , 二分
    tyvj 1402 乌龟棋 dp
    vijos 1057 盖房子 dp 最大子正方形
  • 原文地址:https://www.cnblogs.com/huangqingshi/p/7538346.html
Copyright © 2011-2022 走看看