本文内容
java
HashSet概述函数
HashSet源码分析源码分析
HashSet概述code
HashSet是Set的一种实现,其底层是用HashMap实现的,整个HashSet看起来就像一个包装类!继承
HashSet的继承图以下:接口
HashSet继承了Set、Abstract类,实现了Cloneable 、Serializable 接口。
ci
HashSet实现
rem
看一下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();
底层直接用了HashMap.PRESENT就是用来填充map的value。为什么不用null呢??hash
默认构造函数:
public HashSet() { map = new HashMap<>(); } public HashSet(Collection<? extends E> c) { map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16)); addAll(c); } public HashSet(int initialCapacity, float loadFactor) { map = new HashMap<>(initialCapacity, loadFactor); } public HashSet(int initialCapacity) { map = new HashMap<>(initialCapacity); } HashSet(int initialCapacity, float loadFactor, boolean dummy) { map = new LinkedHashMap<>(initialCapacity, loadFactor); }
前面四个构造函数都容易理解,最后那个,定义一个默认权限的构造函数,并且仍是LinkedHashMap是什么用呢?从注释上得知,是给LinkedHashSet用的。暂时不理它了。
Constructs a new, empty linked hash set. (This package private constructor is only used by LinkedHashSet.) The backing HashMap instance is a LinkedHashMap with the specified initial capacity and the specified load factor.
add方法
public boolean add(E e) { return map.put(e, PRESENT)==null; }
封装了下map,看一下其余的
public boolean remove(Object o) { return map.remove(o)==PRESENT; } public void clear() { map.clear(); } public boolean contains(Object o) { return map.containsKey(o); } public int size() { return map.size(); } public Iterator<E> iterator() { return map.keySet().iterator(); }
都是封装,不看了。
总结
HashSet的底层使用了HashMap,用map的key做为set的结果。因此源码很是简单。