集合之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);
}

 

posted @ 2021-06-14 17:20  山阴路的秋天  阅读(32)  评论(0编辑  收藏  举报