HashSet是如何保证元素不重复的
------解决方案--------------------
分析源代码
private transient HashMap<E,Object> map;
/**
* 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;
}
HashSet的底层是通过HashMap来实现,因为HashMap有key做保证,所有HashMap不会重复,所有HashSet也不会重复,key就相当于我们数据库中保证唯一性的ID字段。
------解决方案--------------------
看hashmap源码
if (e.hash == hash && ((k = e.key) == key
------解决方案--------------------
key.equals(k))) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
先判断的hashCode,hashCode不同,则元素值一定不同。
hashCode相同,但元素未必相同,还需调用equals判断
如果equals为true,则相同,排除此元素