HashSet

HashSet

1
2
3
public class HashSet<E>
extends AbstractSet<E>
implements Set<E>, Cloneable, java.io.Serializable

This class implements the Set interface, backed by a hash table (actually a HashMap instance).
Note that this implementation is not synchronized.
Set s = Collections.synchronizedSet(new HashSet(...));

Abstract

主要实现依赖于HashMap

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class HashSet<E>
extends AbstractSet<E>
implements Set<E>, Cloneable, java.io.Serializable{

private transient HashMap<E,Object> map;
/**
* 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<>();
}
public Iterator<E> iterator() {
return map.keySet().iterator();
}
public boolean remove(Object o) {
return map.remove(o)==PRESENT;
}
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
}

… …

Set

Note: Great care must be exercised if mutable objects are used as set elements.(will modify the value in Set, just like clone–浅拷贝)

… …

***the hashcode of entry in HashMap:table is unmutable, it is fixed when create entry, so add a mutable entry, and then you can change it(Particularly, you can make it be same with others, but its place(or hash) in table is fixed just like before.).When resize the Map, the hashcode will not change. ***

-------------再接再厉更进一步---------------