HashSet为什么元素不重复

打开HashSet源码,发现其内部维护了一个HashMap:

public class HashSet
extends AbstractSet
implements Set, Cloneable, java.io.Serializable
{
static final long serialVersionUID = -5024744406713321676L;

private transient HashMap<E,Object> map;

// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();

/**
 * Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
 * default initial capacity (16) and load factor (0.75).
 */
public HashSet() {
    map = new HashMap<>();
}


}

想知道为什么HashSet不能存放重复对象,那么第一步当然是看它的add方法怎么进行的判重,代码如下:

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

其实,这时候答案已经出来了:HashMap的key是不能重复的,而这里HashSet的元素又是作为了map的key,当然也不能重复了。

HashSet怎么做到保证元素不重复的原因找到了,文章也就结束了。。。等等,顺便看一下HashMap里面又是怎么保证key不重复的吧,代码如下:

public V put(K key, V value) {
if (table == EMPTY_TABLE) {
inflateTable(threshold);
}
if (key == null)
return putForNullKey(value);
int hash = hash(key);
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;

}
其中最关键的一句:

if (e.hash == hash && ((k = e.key) == key || key.equals(k)))
调用了对象的hashCode和equals方法进行的判断,所以又得出一个结论:若要将对象存放到HashSet中并保证对象不重复,应根据实际情况将对象的hashCode方法和equals方法进行重写

转载于https://www.cnblogs.com/nickhan/p/8550655.html

猜你喜欢

转载自blog.csdn.net/qq_34118946/article/details/86250171
今日推荐