HashSet源码解析(JDK1.8)
HashSet实现原理
??HashSet的绝大部分方法都是通过其内置的HashMap实现的,我们向HashSet中存一个元素,实际上就是向其内置的HashMap中存一个键值对,键是我们存的元素,值其实就是一个Object,我们并不关心。因为HashMap中put方法对于存储重复键默认会进行覆盖操作,所以HashSet中不会存储重复元素。因此,只要了解了HashMap的原理,也就知道了HashSet的原理。 ??我们在之前的博客中详细讨论过了HashMap的源码,传送门:最全面的HashMap源码解析(JDK1.8)
HashSet的属性

HashSet的方法
构造方法
空参构造HashSet()

??其实就是通过HashMap的空参构造为内置的HashMap创建实例
HashSet(Collection<? extends E> c)
 ??若传一个Collection c,则是将c中的所有元素都加入到新创建的HashSet中,这里调用的是HashMap(int initialCapacity),HashMap的初始大小将设置为足够放入c中的所有元素,最小为16 ??这里会调用HashSet继承的AbstractSet中的addAll方法,该方法源码如下:  ??其实就是对c中的每个元素调用HashSet中重写的add方法,存入每个元素
HashSet(int initialCapacity, float loadFactor)
 ??其实就是调用HashMap(int initialCapacity, float loadFactor),设置内置HashMap的初始容量和负载因子
HashSet(int initialCapacity)
 ??其实就是调用HashMap(int initialCapacity),设置内置HashMap的初始容量,使用默认负载因子0.75
HashSet(int initialCapacity, float loadFactor, boolean dummy)
 ??这个boolean类型的dummy参数的值其实不重要,多这么一个参数就是为了和其他构造函数区分开,调用这个3个参数的构造函数,将创建LinkedHashMap作为内置的HashMap,LinkedHashMap继承了HashMap,LinkedHashMap保存了记录的插入顺序,在用Iterator遍历LinkedHashMap时,先得到的记录肯定是先插入的。
增删改查方法
??
add(E e)
 ??add(E e)即能增( Create )也能改(Update),其实就是调用内置的HashMap的put方法,键为我们要存的元素,值为PRESENT。HashMap的put方法返回null表示添加成功
remove(Object o)

??其实就是调用了内置的HashMap的remove方法,HashMap的remove方法,若删除成功,会返回value值,否则返回null
其他方法
size()

??调用内置HashMap的size()方法,将返回map中的键值对数量,也就是HashSet中元素的数量
iterator()
 ??返回内置HashMap的键迭代器,也就是HashSet的元素迭代器
contains(Object o)
 ??调用内置HashMap的containsKey方法,而该方法又会调用getNode方法去查找对应的结点
|