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);
    }
  • 相关阅读:
    EF之DataBase添加新字段
    VS 发布MVC网站缺少视图
    解决IE下打印iframe时,页面比例变小的问题
    DataTable求列的最大值、最小值、平均值和样本数
    js的splice和delete
    js获取对象的属性个数
    placeholder
    prompt
    依赖注入
    highcharts离线导出图表
  • 原文地址:https://www.cnblogs.com/wlong-blog/p/14882814.html
Copyright © 2011-2022 走看看