HashSet

作者: 于情于你 | 来源:发表于2021-05-25 11:25 被阅读0次

    HashSet的结构

    public class HashSet<E>
        extends AbstractSet<E>
        implements Set<E>, Cloneable, java.io.Serializable
    {
        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();
    }
    

        HastSet的底层存储结构是一个名字叫做map的HashMap,因为HashSet是单值的,非键值对,把HashSet的值用作了HashMap的Key,Value就是上面代码中的PRESENT。

    构造函数

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

    常用API

        如果元素e不存在Set当中,那么加入元素e,并返回true,否则返回false

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

        如果此集合包含指定的元素则返回true,否则返回false

      public boolean contains(Object o) {
            return map.containsKey(o);
        }
    

        在Set中删除元素o,如果删除成功返回true,否则返回false

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

    相关文章

      网友评论

        本文标题:HashSet

        本文链接:https://www.haomeiwen.com/subject/qpnfsltx.html