HashMap的源码解析:https://mp.csdn.net/console/editor/html/106188425
HashSet:Java中的一个集合类,该容器不允许包含重复的数值
public class HashSet<E>extends AbstractSet<E>implements Set<E>, Cloneable, java.io.Serializable
{static final long serialVersionUID = -5024744406713321676L;private transient HashMap<E,Object> map;// Dummy value to associate with an Object in the backing Mapprivate static final Object PRESENT = new Object();
可以看出,HashSet类继承了AbstractSet类,并且实现了Cloneable,Serizalizable接口。
HashSet是基于HashMap实现的,因此建立了map变量
PRESENT是用来填充map中的value,定义为Object类型。
下面先来看HashSet的构造方法:
1.无参构造
public HashSet() {map = new HashMap<>();}2.参数为一个HashSet的实例对象
public HashSet(Collection<? extends E> c) {map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16));addAll(c);}3.参数为初始化的大小以及负载因子
public HashSet(int initialCapacity, float loadFactor) {map = new HashMap<>(initialCapacity, loadFactor);}4. 参数为初始化的大小
public HashSet(int initialCapacity) {map = new HashMap<>(initialCapacity);}5.参数为初始化的大小,负载因子,以及一个标志位
HashSet(int initialCapacity, float loadFactor, boolean dummy) {map = new LinkedHashMap<>(initialCapacity, loadFactor);}//第五个构造函数为默认修饰符default,所以为包访问权限,只要是为了支持LinkedHashSet
接下来的iterator(),size(),isEmpty(),containss(),clear()方法都是基本上直接调用了HashMap的方法:
public Iterator<E> iterator() {return map.keySet().iterator();}public int size() {return map.size();}public boolean isEmpty() {return map.isEmpty();}public boolean contains(Object o) {return map.containsKey(o);}public void clear() {map.clear();}
add(),remove()把要加入,移除的值当作key,初始定义的PRESENT当作value来进行实现的
public boolean add(E e) {return map.put(e, PRESENT)==null;}public boolean remove(Object o) {return map.remove(o)==PRESENT;}
clone()方法:
@SuppressWarnings("unchecked")public Object clone() {try {HashSet<E> newSet = (HashSet<E>) super.clone();newSet.map = (HashMap<E, Object>) map.clone();return newSet;} catch (CloneNotSupportedException e) {throw new InternalError(e);}}
@SuppressWarnings("unchecked")表示告诉编译器忽视unchecked警告
直接调用了父类的clone方法
这里的clone是深拷贝,当原来的本体发生了改变,克隆体不会变,看下面这个例子:
public class test {@SuppressWarnings("unchecked")public static void main(String[] args) {HashSet<Integer> set = new HashSet<>();set.add(1);set.add(2);set.add(3);set.add(4);set.add(5);HashSet<Integer> set1;set1 = (HashSet<Integer>) set.clone();System.out.println(set+" "+set1);set.remove(5);set.add(6);System.out.println(set+" "+set1);}
}输出的结果为:
[1, 2, 3, 4, 5] [1, 2, 3, 4, 5]
[1, 2, 3, 4, 6] [1, 2, 3, 4, 5]