1.set中的元素是不重复的。如果添加的是已有的数据, 会用现在的值替换原来的值,并返回原来的值。 set添加元素的动作其实是hashmap的put操作
a. 创建hashSet对象
/**
* 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<>();
}
b. 添加元素
其中PRESENT是定义的一个final变量,作为hashmap的value。
private static final Object PRESENT = new Object();
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
c. hashmap的put操作
public V put(K key, V value) {
if (table == EMPTY_TABLE) {
inflateTable(threshold);
}
if (key == null)
return putForNullKey(value);
int hash = hash(key);
int i = indexFor(hash, table.length);
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value; // 用新值替换掉原有的值
e.recordAccess(this);
return oldValue; // 返回原来的值
}
}
modCount++;
addEntry(hash, key, value, i);
return null;
}