zoukankan      html  css  js  c++  java
  • 集合之HashSet源码解析

    hashSet 类图:

    hashset 本质上为hashMap 的key, 常用于集合去重。

    构造函数:

    public HashSet() {
        map = new HashMap<>();
    }
    
    public HashSet(Collection<? extends E> c) {
        // (int) (c.size()/.75f) + 1 避免扩容
        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);
    }
    
    HashSet(int initialCapacity, float loadFactor, boolean dummy) {
        map = new LinkedHashMap<>(initialCapacity, loadFactor); 
    }

    添加单个元素: value为PRESENT

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

     添加多个元素:

     public boolean addAll(Collection<? extends E> c) {
            boolean modified = false;
            for (E e : c)
                if (add(e))
                    modified = true;
            return modified;
        }

    移除单个元素:

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

    全部清除:clear

     public void clear() {
            map.clear();
        }

    转化为数组:

    @Override
    public Object[] toArray() {
        return map.keysToArray(new Object[map.size()]);
    }
    
    @Override
    public <T> T[] toArray(T[] a) {
        return map.keysToArray(map.prepareArray(a));
    }

    查找是否包含某个元素:

    public boolean contains(Object o) {
        return map.containsKey(o);
    }
  • 相关阅读:
    Node.js运行Vue项目
    DotNetCore知识栈
    Building gRPC Client iOS Swift Note Taking App
    React Native
    Node.js 教程
    SQL 在线教程&在线练习平台
    RxSwift + Moya + ObjectMapper
    浅谈常用的几种web攻击方式
    让MyEclipse支持mac的Retina屏解决字体模糊的问题
    Java设计模式中的单例模式
  • 原文地址:https://www.cnblogs.com/wlong-blog/p/14882814.html
Copyright © 2011-2022 走看看