集合源码分析(三)HashSet实现(JDK1.8)

版权声明:本文为博主原创文章,转载添加原文链接 https://blog.csdn.net/qq_34190023/article/details/80879389

HashSet。不保证有序(因为底层是hashmap),允许使用null(因为hashmap允许)

public class HashSet<Eextends AbstractSet<E>
   
implements Set<E>, Cloneable, java.io.Serializable

private transient HashMap<E,Object> map;  // 可以看出底层维护了一个hashmap

private staticfinal Object PRESENT = new Object(); // 定义一个虚拟的Object对象作为HashMapvalue,将此对象定义为static final

public HashSet() {
   
map = new HashMap<>();
}

public HashSet(Collection<? extends E> c) {

//实际底层使用默认的加载因子0.75和足以包含指定 

//collection中所有元素的初始容量来创建一个HashMap 
   
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 Iterator<E> iterator() {
   
return map.keySet().iterator();
}

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

对于HashSet中保存的对象,请注意正确重写其 equals 和 hashCode方法,以保证放入的对象的唯一性。

猜你喜欢

转载自blog.csdn.net/qq_34190023/article/details/80879389