对于HashSet而言,它是基于HashMap实现的,底层采用HashMap来保存元素的。今天我们就简单的分析一下它的实现。人生,总会有不期而遇的温暖,和生生不息的希望。
HashSet的简单分析
一、hashSet的成员变量组成
public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, java.io.Serializable
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的构造方法,是创建一个hashMap。
public HashSet() {
map = new HashMap<>();
}
二、hashSet的一些操作也是基于上述创建的hashMap的
public Iterator<E> iterator() {
return map.keySet().iterator();
}public int size() {
return map.size();
}public boolean isEmpty() {
return map.isEmpty();
}
public boolean contains(Object o) {
return map.containsKey(o);
}public boolean add(E e) {
return map.put(e, PRESENT)==null; // PRESENT是hashSet的成员变量
}public boolean remove(Object o) {
return map.remove(o)==PRESENT; // PRESENT是hashSet的成员变量
}public void clear() {
map.clear();
}
友情链接
- 关于hashMap的原理说明:http://www.cnblogs.com/huhx/p/baseusejavahashmap1.html