java.util.Set#add(E)内部调用jav.util.Map#put(K,V)传递您尝试添加为键的元素,其中它检查当前集合中是否存在与键的 哈希码具有相同哈希码的元素(其中键是您尝试插入的元素),并且它还检查是否相等使用equals()方法.如果哈希码或相等的测试失败,它只会添加到Set.如果hashcode和equal test都通过,那么它只是用当前值替换旧值.下面是Set#add()和Map#put()的源代码.
public boolean add(E e) {
217 return map.put(e, PRESENT)==null;
218 }
Run Code Online (Sandbox Code Playgroud)
public V put(K key, V value) {
387 if (key == null)
388 return putForNullKey(value);
389 int hash = hash(key.hashCode());
390 int i = indexFor(hash, table.length);
391 for (Entry<K,V> e = table[i]; e != null; e = e.next) {
392 Object k;
393 if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
394 V oldValue = e.value;
395 e.value = value;
396 e.recordAccess(this);
397 return oldValue;
398 }
399 }
400
401 modCount++;
402 addEntry(hash, key, value, i);
403 return null;
404 }
Run Code Online (Sandbox Code Playgroud)