ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
[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; } ~~~