前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >HashSet源码学习

HashSet源码学习

作者头像
晓果冻
发布2022-09-08 12:41:24
2440
发布2022-09-08 12:41:24
举报
文章被收录于专栏:一直在努力的Java菜鸡er

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);
        }
    }
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • HashSet源码学习
    • UML图(没实现SortedSet,无序的)
      • 属性
        • 构造方法
          • 增删操作
            • 其它工具方法
              • 为什么map可以实例化
              领券
              问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档