zl程序教程

您现在的位置是:首页 >  Java

当前栏目

HashSet源码解析

2023-02-18 16:34:05 时间

转载请以链接形式标明出处: 本文出自:103style的博客

base on jdk_1.8.0_77


目录

  • HashSet的全局变量
  • HashSet的构造方法
  • HashSet的数据操作方法
  • 小结

HashSet的全局变量

  • private transient HashMap<E,Object> map; 维护了一个HashMap
  • private static final Object PRESENT = new Object(); 保存进HashMap中的值。

HashSet的构造方法

  • 即调用了HashMap的各种初始化方法。
public HashSet() {
    map = new HashMap<>();
}
public HashSet(Collection<? extends E> c) {
    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);
}

HashSet的数据操作方法

  • 可以发现HashSet的数据操作都是通过构建的全局变量HashMap完成的。
public boolean contains(Object o) {
    return map.containsKey(o);
}
public boolean add(E e) {
    return map.put(e, PRESENT) == null;
}
public boolean remove(Object o) {
    return map.remove(o) == PRESENT;
}
public void clear() {
    map.clear();
}
public int size() {
    return map.size();
}
public boolean isEmpty() {
    return map.isEmpty();
}
public Iterator<E> iterator() {
    return map.keySet().iterator();
}

小结

  • HashSet<E>实际上就是通过HashMap保存 keyE ,值为PRESENT = new Object()
  • 对应的数据操作即为HashMapkey 的操作。

HashMap源码解析


以上