Hashset的底层是HashMap
源码如下:
static final long serialVersionUID = -5024744406713321676L;
private transient HashMap
// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();
_/*
Constructs a new, empty set; the backing HashMap instance has
default initial capacity (16) and load factor (0.75).
/
_public HashSet() {
map = new HashMap<>();
}
明显map就是HashSet的操作对象,因为它在构造方法中初始化
我们来看它的add方法
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
可以看出hashset实际上用的是hashmap的key的不可重复性
HashSet本身无序,而且没有键值对,所以没法定义get方法

上述代码如果使用HashSet
会报ConcurrentModificationException
解决方法是换成工具类或者写时复制
详情参考ArrayList
