在看视频时,发现老毕在讲HashSet的时候,着重强调了保证唯一性的问题。并且说是两个验证,hashCode和equals.
老毕是通过实验的方式讲解的,但是,老汉本着研究岛国大片的精神,有仔细的观察了下代码:
HashSet.class
/**
* 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;
}
外套脱了,就成内裤了。。。找map:
/**
* Associates the specified value with the specified key in this map.
* If the map previously contained a mapping for the key, the old
* value is replaced.
*
* @param key key with which the specified value is to be associated
* @param value value to be associated with the specified key
* @return the previous value associated with <tt>key</tt>, or
* <tt>null</tt> if there was no mapping for <tt>key</tt>.
* (A <tt>null</tt> return can also indicate that the map
* previously associated <tt>null</tt> with <tt>key</tt>.)
*/
public V put(K key, V value) {
if (key == null)
return putForNullKey(value);
int hash = hash(key.hashCode());
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;
}
柳暗花明又一村。。。
高深的看不懂,但是,比较直观的就是,先验证了hash值,如果不同,没必要用equals。所以,如果发生了hashCode的值相同的情况,就必须做两次判断。。。
话说,好像真的很难的样子。。。public V ...这是个什么东东?
语言不通不要紧,只要我们用心体会。。。