温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

好程序员分享HashSet实现去除重复元素

发布时间:2020-08-08 00:00:04 来源:ITPUB博客 阅读:166 作者:好程序员IT 栏目:编程语言

   好程序员 分享 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))) {                

     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 双重保障去除重复元素


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI