【Java】HashSet实现去除重复元素

首先 HashSet当中有自己封装了add方法
public boolean add(E e) { return map.put(e, PRESENT)==null; }
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; 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; } 这个方法均为封装并直接能调用add方法使用
由此可见for循环,遍历table的元素
1.由于hash码值的不同,证明是新元素,就直接保存其中
如果没有元素和传入值的hash相等则判定为元素在table不存在,也直接保存添加到table内
2.如果hash码值相同,切equles判断相等,证明元素存在,则舍弃
3.如果hash码值相同,且equles判断不相等,证明元素不存在,则添加
如果元素和传入值hash相等,接下来会调用equles方法判断,依然相等的会认为已经存在的元素
不添加并结束,否则继续添加
由此hashcode()和equles()是核心关键点
hash值是什么
可以通过对象的成员变量计算出来
成员数值相加计算并获取hash值
类中重写方法示例:
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
因为对象的name,age有所不同导致相加计算结果也会不同
但是有可能存在对象成员变量不同,hash码相同的情况
因为必须再重写另外一个方法
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
equles实现分别对name,age进行判断是否相等

通过这两个方法,在向hashSet调用add添加元素时,就能准确保证判断元素是否存在
比较hash码同时比较equles 双重保障去除重复元素

猜你喜欢

转载自blog.csdn.net/JACK_SUJAVA/article/details/107089910