🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
[TOC] HashSet内部使用HashMap的key列来存储数据 ## 构造函数 ~~~ public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, java.io.Serializable { static final long serialVersionUID = -5024744406713321676L; //使用HashMap来存储,存在key里 private transient HashMap<E,Object> map; // 空对象 作为value private static final Object PRESENT = new Object(); /** * Constructs a new, empty set; the backing <tt>HashMap</tt> instance has * default initial capacity (16) and load factor (0.75). */ public HashSet() { map = new HashMap<>(); } } ~~~ ## add ~~~ public boolean add(E e) { return map.put(e, PRESENT)==null; } ~~~ ## remove ~~~ public boolean remove(Object o) { return map.remove(o)==PRESENT; } ~~~