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); }