1. 程式人生 > 其它 >集合之HashSet原始碼解析

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