java中set集合中元素不重复是根据什么来判断的

如题所述

源码HashSet.add:
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}

源码HashMap.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;
}

由此可见,HashSet是根据放入object的hashcode做判断,然后遍历查找是否有hashcode值和键相同的元素。若存在则返回已有元素,不在entry里再添加
这段:
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
若不存在,返回null,并添加:
addEntry(hash, key, value, i);
return null;
然后你就能根据return map.put(e, PRESENT)==null; 这个得知你是否添加成功,换句话说就是是否存在。true添加成功不存在,false添加失败存在

因为只有继承了Object的类才具有hashcode,所以基本类型如int都是由他们的包装类
另外加一点泛型的知识,若你的Set用到了泛型,E则代表泛型类型。否则为Object
温馨提示:答案为网友推荐,仅供参考
第1个回答  2017-01-09
 /**
     * 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&nbsp;?&nbsp;e2==null&nbsp;:&nbsp;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.add说明

本回答被提问者采纳
相似回答