答案:需要hash码值,同时还要结合equles方法,方能否能够保证hashset 的值不重复
HashSet 类中的add()方法:
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
类中map和PARENT的定义:
private transient HashMap<E,Object> map;
// Dummy value to associate with an Object in the backing Map用来匹配Map中后面的对象的一个虚拟值
private static final Object PRESENT = new Object();
put()方法:
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;
}
参考链接:http://blog.csdn.net/u010698072/article/details/52802179