侧边栏壁纸
博主头像
晓果冻博主等级

一个热爱生活的95后精神小伙

  • 累计撰写 131 篇文章
  • 累计创建 15 个标签
  • 累计收到 67 条评论

目 录CONTENT

文章目录

HashSet源码学习

晓果冻
2020-10-22 / 0 评论 / 2 点赞 / 478 阅读 / 3,150 字
温馨提示:
本文最后更新于 2021-10-26,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

HashSet源码学习

UML图(没实现SortedSet,无序的)

image-20210816100300166

属性

static final long serialVersionUID = -5024744406713321676L;
/*底层是HasMap来实现的,transient?不能使用jdk的默认序列化方式了, 但是jdk
在进行对象的序列化的时候, 会通过反射判断对象中是否有重写的writeObject和
readObject方法, 从而调用重写的方法。*/
private transient HashMap<E,Object> map;
/*为什么不直接赋值null?考虑到HashMap put时,返回null时不知道
是第一插入害死真的插入null值*/
private static final Object PRESENT = new Object();

构造方法

/*
底层都是围绕HashMap展开的,负载因子,初始容量等
*/
	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);
    }
    
    /*
    非public,LinkedHashSet专用,boolean dummy无实际意义,仅
    作为和其它构造方法的区分
    */
    HashSet(int initialCapacity, float loadFactor, boolean dummy无实际意义) {
        map = new LinkedHashMap<>(initialCapacity, loadFactor);
    }

增删操作

//底层都是调用hashmap的方法,hashmap学会就ok
	public boolean add(E e) {
        return map.put(e, PRESENT)==null;
    }
    
     public boolean remove(Object o) {
        return map.remove(o)==PRESENT;
    }
    

其它工具方法

	public int size() {
        return map.size();
    }
    
    public boolean isEmpty() {
        return map.isEmpty();
    }
    
    public boolean contains(Object o) {
        return map.containsKey(o);
    }
    
    public void clear() {
        map.clear();
    }

为什么map可以实例化

private void writeObject(java.io.ObjectOutputStream s)
        throws java.io.IOException {
        // Write out any hidden serialization magic
        s.defaultWriteObject();

        // Write out HashMap capacity and load factor
        s.writeInt(map.capacity());
        s.writeFloat(map.loadFactor());

        // Write out size
        s.writeInt(map.size());

        // Write out all elements in the proper order.
        for (E e : map.keySet())
            s.writeObject(e);
    }

    /**
     * Reconstitute the <tt>HashSet</tt> instance from a stream (that is,
     * deserialize it).
     */
    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException {
        // Read in any hidden serialization magic
        s.defaultReadObject();

        // Read capacity and verify non-negative.
        int capacity = s.readInt();
        if (capacity < 0) {
            throw new InvalidObjectException("Illegal capacity: " +
                                             capacity);
        }

        // Read load factor and verify positive and non NaN.
        float loadFactor = s.readFloat();
        if (loadFactor <= 0 || Float.isNaN(loadFactor)) {
            throw new InvalidObjectException("Illegal load factor: " +
                                             loadFactor);
        }

        // Read size and verify non-negative.
        int size = s.readInt();
        if (size < 0) {
            throw new InvalidObjectException("Illegal size: " +
                                             size);
        }
        // Set the capacity according to the size and load factor ensuring that
        // the HashMap is at least 25% full but clamping to maximum capacity.
        capacity = (int) Math.min(size * Math.min(1 / loadFactor, 4.0f),
                HashMap.MAXIMUM_CAPACITY);

        // Constructing the backing map will lazily create an array when the first element is
        // added, so check it before construction. Call HashMap.tableSizeFor to compute the
        // actual allocation size. Check Map.Entry[].class since it's the nearest public type to
        // what is actually created.

        SharedSecrets.getJavaOISAccess()
                     .checkArray(s, Map.Entry[].class, HashMap.tableSizeFor(capacity));

        // Create backing HashMap
        map = (((HashSet<?>)this) instanceof LinkedHashSet ?
               new LinkedHashMap<E,Object>(capacity, loadFactor) :
               new HashMap<E,Object>(capacity, loadFactor));

        // Read in all elements in the proper order.
        for (int i=0; i<size; i++) {
            @SuppressWarnings("unchecked")
                E e = (E) s.readObject();
            map.put(e, PRESENT);
        }
    }
2

评论区