HashSet数据结构介绍
hashSet无参构造函数
//hashset的默认构造函数,实际是创造一个hashmap对象
public HashSet() {
map = new HashMap<>();
}
因为hashmap的扩展因子是0.75,及当0.75时就自动扩展,用构造的函数集合大小去初始 化hashmap,用扩 展集合的大小除以0.75+1与16比较,取较大的值作为初始化hashmap集合 的大小
public HashSet(Collection<? extends E> c) {
map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16));
addAll(c);
}
hashset通过固定集合大小初始化
public HashSet(int initialCapacity) {
map = new HashMap<>(initialCapacity);
}
hashSet添加集合元素
//hashSet添加集合元素也是通过hashMap添加的集合元素,如果集合存在该元素,则返回false,不存在则返回true
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
hashSet删除元素
//通过hashmap的删除方法删除集合元素, 删除成功返回true,失败false
public boolean remove(Object o) {
return map.remove(o)==PRESENT;
}
HashSet清空集合元素
//hashSet清空集合元素,是通过hashmap的clear清楚方法清空集合的,
public void clear() {
map.clear();
}
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。