HashSet中add()函数的理解

本文深入解析了HashSet的add()方法实现原理,包括其构造函数、如何利用HashMap存储元素以及add()方法的具体流程,帮助理解HashSet的工作机制。

HashSet实现了set接口,也是日常开发中比较常用的类,今天通过对HashSet add()方法源码的分析进一步加深对HashSet的理解。

首先先看下HashSet的构造函数,代码如下:

  1. /**
  2. * Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
  3. * default initial capacity (16) and load factor (0.75).
  4. */
  5. public HashSet() {
  6. map = new HashMap<>();
  7. }
  1. /**
  2. * Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
  3. * the specified initial capacity and the specified load factor.
  4. *
  5. * @param initialCapacity the initial capacity of the hash map
  6. * @param loadFactor the load factor of the hash map
  7. * @throws IllegalArgumentException if the initial capacity is less
  8. * than zero, or if the load factor is nonpositive
  9. */
  10. public HashSet(int initialCapacity, float loadFactor) {
  11. map = new HashMap<>(initialCapacity, loadFactor);
  12. }
  1. /**
  2. * Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
  3. * the specified initial capacity and default load factor (0.75).
  4. *
  5. * @param initialCapacity the initial capacity of the hash table
  6. * @throws IllegalArgumentException if the initial capacity is less
  7. * than zero
  8. */
  9. public HashSet(int initialCapacity) {
  10. map = new HashMap<>(initialCapacity);
  11. }

这三个HashSet的构造函数说明HashSet本质上都是构建了一个HashMap,第一个构造函数仅仅是构建了一个简单的HashMap,用了HashMap默认的初始容量(16)以及默认LOAD_FACTOR(0.75f);第二个构造函数构建HashMap时会指定HashMap的初始容量以及LOAD_FACTOR;第三个构造函数构建HashMap时会指定HashMap的初始容量。

注意:这里初始容量应尽量设置为2的幂,这样能够保证键值对更加均匀地分布在HashMap上。

接下来我们来看下本文的核心HashSet的add()方法,源代码如下:

  1. /**
  2. * Adds the specified element to this set if it is not already present.
  3. * More formally, adds the specified element <tt>e</tt> to this set if
  4. * this set contains no element <tt>e2</tt> such that
  5. * <tt>(e==null ? e2==null : e.equals(e2))</tt>.
  6. * If this set already contains the element, the call leaves the set
  7. * unchanged and returns <tt>false</tt>.
  8. *
  9. * @param e element to be added to this set
  10. * @return <tt>true</tt> if this set did not already contain the specified
  11. * element
  12. */
  13. public boolean add(E e) {
  14. return map.put(e, PRESENT)==null;
  15. }

这里方法注释的意思是添加指定的element如果该set集合不包含该element,如果该set集合已包含将要新增的element,则不对set进行任何操作并返回false;若该set集合不包含将要新增的element,则将该element添加至该set集合中并返回true。add()方法中的e即为添加的element而PRESENT则为一个虚拟的假值,不用在意。PRESENT的定义代码如下:

  1. // Dummy value to associate with an Object in the backing Map
  2. private static final Object PRESENT = new Object();

接下来来看下add()方法的具体实现代码,map.put()方法最终调用的是HashMap的putVal()方法其中HashSet新增的element 其实就是HashMap的key。源代码及注释如下:

  1. /**
  2. * Implements Map.put and related methods
  3. *
  4. * @param hash hash for key
  5. * @param key the key
  6. * @param value the value to put
  7. * @param onlyIfAbsent if true, don't change existing value
  8. * @param evict if false, the table is in creation mode.
  9. * @return previous value, or null if none
  10. */
  11. final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
  12. boolean evict) {
  13. Node<K,V>[] tab; Node<K,V> p; int n, i;
  14. if ((tab = table) == null || (n = tab.length) == 0) //HashMap底层存储为 Node<K,V>[]结构若当前 Node<K,V>[]的length为0则resize
  15. n = (tab = resize()).length;//获取resize后的链表length
  16. if ((p = tab[i = (n - 1) & hash]) == null)//这里通过length及key的hash值计算element存储的具体index若该节点无元素则直接存入
  17. tab[i] = newNode(hash, key, value, null);//新建新node并存入 Node<K,V>[]
  18. else {
  19. Node<K,V> e; K k;
  20. if (p.hash == hash && //若tab[i = (n - 1) & hash]上有元素且该元素的hash值与新增的key.hash相同则e=p
  21. ((k = p.key) == key || (key != null && key.equals(k))))
  22. e = p;
  23. else if (p instanceof TreeNode)//若tab[i = (n - 1) & hash]上的元素呈树形(红黑树)排布则将新增element存储入该红黑树中
  24. e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);//存储后返回新增的树形节点
  25. else {//若tab[i = (n - 1) & hash]呈链表形式排布则找到末尾节点将新增元素存在末尾节点之后
  26. for (int binCount = 0; ; ++binCount) {
  27. if ((e = p.next) == null) {//将新增元素存储在末尾
  28. p.next = newNode(hash, key, value, null);//新增节点
  29. if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st//若元素数量超过阈值则自动将链表转为树形结构(红黑树)
  30. treeifyBin(tab, hash);//转为树形结构(红黑树)
  31. break;
  32. }
  33. if (e.hash == hash &&//若链表中的某一节点hash和key与新增元素的key.hash以及key相同break
  34. ((k = e.key) == key || (key != null && key.equals(k))))
  35. break;
  36. p = e;
  37. }
  38. }
  39. if (e != null) { // existing mapping for key
  40. V oldValue = e.value; //获取element旧的value
  41. if (!onlyIfAbsent || oldValue == null) //这里onlyIfAbsent为false
  42. e.value = value;//更新value
  43. afterNodeAccess(e);//预留函数不用管
  44. return oldValue;//返回旧的value
  45. }
  46. }
  47. ++modCount;//HashMap修改次数+1
  48. if (++size > threshold)//size+1 若size大于阈值(LOAD_FACTOR * INITIAL_CAPACITY)则resize
  49. resize();//resize
  50. afterNodeInsertion(evict);//预留函数不用理会
  51. return null;//若为新节点则返回null
  52. }

通过分析HashMap的putVal()方法,我们可以知道事实上HashMap定位元素的方式都是通过key以及key对应的hash。在putVal()方法中,如果新增的key在HashMap中不存在,则会直接通过key的hash值以及HashMap的length进行&运算然后得到存储的index并直接存入新的键值对同时返回null;若key已在HashMap中存在,则根据实际情况检索并得到key对应的键值对,然后更新value并返回旧的value。

了解的HashMap的putVal()原理后,再回过头来看HashSet的add()源代码:

  1. public boolean add(E e) {
  2. return map.put(e, PRESENT)==null;
  3. }

我们可以知道:当新增的element e (即新增HashMap中的key)不存在于HashMap中,那么HashMap的putVal()方法会返回null,从而使add()方法返回true即新增成功;若新增的element e (即新增HashMap中的key)已存在于HashMap中,那么HashMap的putVal()方法会返回旧的value即dummy value (new Object()),从而使add()方法返回false即新增失败。

以上就是HashSet add()方法的解析,若有不正确的地方请大家指正,谢谢!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值