public class NoSafeHashSet {
public static void main(String[] args) {
Set<Object> set = new HashSet<>();
for (int i = 0; i < 30; i++) {
new Thread(() -> {
set.add(UUID.randomUUID().toString().substring(0,8));
System.out.println(set);
}, String.valueOf(i)).start();
}
}
}
解决方法:
1 使用 Collections.synchronizedSet(new HashSet<>()); 代替
2 使用 new CopyOnWriteArraySet<>();代替
注意HashSet的底层结构是HashMap,大小是16负载因子是0.75的HashMap
/**
* Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
* default initial capacity (16) and load factor (0.75).
*/
public HashSet() {
map = new HashMap<>();
}
问题:hashSet.add("a")这样的代码,Map是k-v结构的,这里为什么是一个参数
源码这里其实是在Map里放了两个参数,他是将这个a作为map的key,而value是一个对象
/**
* Adds the specified element to this set if it is not already present.
* More formally, adds the specified element <tt>e</tt> to this set if
* this set contains no element <tt>e2</tt> such that
* <tt>(e==null ? e2==null : e.equals(e2))</tt>.
* If this set already contains the element, the call leaves the set
* unchanged and returns <tt>false</tt>.
*
* @param e element to be added to this set
* @return <tt>true</tt> if this set did not already contain the specified
* element
*/
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();