源码阅读 - HashSet

本文中涉及HashMap的知识参考HashMap源码阅读

0. HashSet是什么

  • 实现Set接口,所以元素不重复,最多一个null元素
  • 不保证元素的存储顺序

1. 实现的本质

HashSet是通过HashMap来存储元素的,也是通过它来保证Key的唯一性
在这个HashMap中要存储的元素作为KeyPRESENT作为Value来进行存储

private transient HashMap map;
// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();

2. 主要api解析

2.1 构造函数

在构造函数中初始化HashMap,其中的capacityloadFactor也是指定HashMapcapacityloadFactor

public HashSet()
public HashSet(int initialCapacity)
public HashSet(int initialCapacity, float loadFactor)
public HashSet(Collection c)

2.2 add方法

map中存入一个元素,key是需要存储的元素,valuePRESENT,由于HashMapkey是唯一的,所以Set中的元素就是唯一的,不能重复

/**
 * Adds the specified element to this set if it is not already present.
 * More formally, adds the specified element e to this set if
 * this set contains no element e2 such that
 * (e==null ? e2==null : e.equals(e2)).
 * If this set already contains the element, the call leaves the set
 * unchanged and returns false.
 *
 * @param e element to be added to this set
 * @return true if this set did not already contain the specified
 * element
 */
public boolean add(E e) {
    return map.put(e, PRESENT)==null;
}

2.3 remove方法

同样的,remove方法也是从map中删除元素

/**
 * Removes the specified element from this set if it is present.
 * More formally, removes an element e such that
 * (o==null ? e==null : o.equals(e)),
 * if this set contains such an element.  Returns true if
 * this set contained the element (or equivalently, if this set
 * changed as a result of the call).  (This set will not contain the
 * element once the call returns.)
 *
 * @param o object to be removed from this set, if present
 * @return true if the set contained the specified element
 */
public boolean remove(Object o) {
    return map.remove(o)==PRESENT;
}

2.4 遍历

遍历是遍历mapkeySet

/**
 * Returns an iterator over the elements in this set.  The elements
 * are returned in no particular order.
 *
 * @return an Iterator over the elements in this set
 * @see ConcurrentModificationException
 */
public Iterator iterator() {
    return map.keySet().iterator();
}

3. 参考

  1. HashSet源码build 1.8.0_121-b13版本

你可能感兴趣的:(源码阅读 - HashSet)