HashSet数据结构:
// 持有一个HashMap的对象 private transient HashMap<E,Object> map;
初始化方法:
public HashSet() { map = new HashMap<>(); }
HashSet的增删改查操作都是调用HashMap的方法实现的:
//PRESENT是一个空对象;PRESENT = new Object(); public boolean add(E e) { return map.put(e, PRESENT)==null; } public boolean remove(Object o) { return map.remove(o)==PRESENT; } public boolean contains(Object o) { return map.containsKey(o); }
LinkedHashSet继承了HashSet
初始化方法:
public LinkedHashSet() { super(16, .75f, true); } HashSet(int initialCapacity, float loadFactor, boolean dummy) { map = new LinkedHashMap<>(initialCapacity, loadFactor); }
HashMap、LinkedHashMap,HashSet,LinkedHashSet之间的关系: