package collection.set; import java.util.HashSet; /** * HashSet:不包含重复元素的集合 * 底层数据结构是哈希表 * 此类实现 Set 接口,由哈希表(实际上是一个 HashMap 实例)支持。 * 它不保证 set 的迭代顺序;特别是它不保证该顺序恒久不变。 * 此类允许使用 null 元素。 * * HashSet集合存储元素: * 要保证元素的唯一性,需要重写hashCode()和equals()方法 */ public class HashSetDemo { public static void main(String[] args) { /* 存储字符串并遍历 */ //创建集合对象 HashSet<String> hs = new HashSet<String>(); //添加元素 hs.add("hello"); hs.add("world"); hs.add("hello"); //遍历 for (String s : hs){ System.out.println(s); } //forEach hs.forEach(System.out::println); } }
//创建集合对象 HashSet<String> hs = new HashSet<String>(); //添加元素 hs.add("hello"); hs.add("world"); hs.add("hello"); //源码 public boolean add(E e) { return map.put(e, PRESENT)==null; } static final int hash(Object key) { int h; return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); } public V put(K key, V value) { return putVal(hash(key), key, value, false, true); } //hash值和元素的hashCode()方法相关 final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) { //元素为节点的数组 哈希表一种结构实现 Node<K,V>[] tab; Node<K,V> p; int n, i; //如果哈希表未初始化,就对其初始化 if ((tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length; // 根据对象的哈希值计算对象的存储位置,如果位置没有元素,就存储元素 if ((p = tab[i = (n - 1) & hash]) == null) tab[i] = newNode(hash, key, value, null); else { Node<K,V> e; K k; /* 存入的元素和以前的元素比较哈希值 如果哈希值不同,会继续向下执行,把元素添加到集合 如果哈希值相同,会调用对象的equals方法比较 如果返回false,会继续向下执行,把元素添加到集合 如果返回true, e = p,说明元素重复,不存储 */ if (p.hash == hash && //对象的比较 对象是不是null ((k = p.key) == key || (key != null && key.equals(k)))) e = p; else if (p instanceof TreeNode) e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value); else { for (int binCount = 0; ; ++binCount) { if ((e = p.next) == null) { p.next = newNode(hash, key, value, null); if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st treeifyBin(tab, hash); break; } if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) break; p = e; } } if (e != null) { // existing mapping for key V oldValue = e.value; if (!onlyIfAbsent || oldValue == null) e.value = value; afterNodeAccess(e); return oldValue; } } ++modCount; if (++size > threshold) resize(); afterNodeInsertion(evict); return null; }