HashSet源码学习

2022-09-08 12:41:24 浏览数 (1)

HashSet源码学习

UML图(没实现SortedSet,无序的)
属性
代码语言:javascript复制
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();
构造方法
代码语言:javascript复制
/*
底层都是围绕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);
    }
增删操作
代码语言:javascript复制
//底层都是调用hashmap的方法,hashmap学会就ok
	public boolean add(E e) {
        return map.put(e, PRESENT)==null;
    }
    
     public boolean remove(Object o) {
        return map.remove(o)==PRESENT;
    }
其它工具方法
代码语言:javascript复制
	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可以实例化
代码语言:javascript复制
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);
        }
    }

0 人点赞