This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element.
HashSet实现了Set接口,其本质是一个HashMap,只使用到了HashMap的key值,value是一个固定的值。对HashSet进行迭代的时候,不能保证其迭代的顺序,其允许添空值。
简单例子如下:
@SuppressWarnings(value = { "all" })
public class TestHashSet {
public static void main(String[] args) {
Set set=new HashSet();
set.add("数学");
set.add("化学");
set.add("物理");
set.add("生物");
set.add("政治");
}
}
HashSet部分源码:
//底层用于用一个HashMap对值进行存放
private transient HashMap<E,Object> map;
//对HashMap的value统一的设置为相同的一个object
private static final Object PRESENT = new Object();
//这里可以看出创建HashSet的时候,实际上是创建了一个HashMap
//其容量大小为16,负载因子为0.75
public HashSet() {
map = new HashMap<>();
}
......
//迭代的时候,都是调用相应map的方法
public Iterator<E> iterator() {
return map.keySet().iterator();
}
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
总结:
HashSet的本质是一个HashMap,只是其value是一个固定的,相同的object,其它操作都是操作相应的HashMap的方法。