你一定听说过HashSet就是通过HashMap实现的
相信我,翻一翻HashSet的源码,秒懂!!
其实很多东西,只是没有静下心来看,只要去看,说不定一下子就明白了……
HashSet
两个属性:
private transient HashMap<E,Object> map;
// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();
所有HashSet的操作都是通过对其属性map操作实现的,map的key是HashSet,map的value都是PRESENT(傀儡)
LinkedHashSet
继承了HashSet,其属性map用的是LinkedHashMap
// LinkedHashSet中
public LinkedHashSet() {
super(16, .75f, true);
} // HashSet中
HashSet(int initialCapacity, float loadFactor, boolean dummy) {
map = new LinkedHashMap<>(initialCapacity, loadFactor);
}
TreeSet
同HashMap的两个属性,map用的是TreeMap
private transient NavigableMap<E,Object> m;
// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object(); public TreeSet() {
this(new TreeMap<E,Object>());
}