引以为戒:避免在Set中使用未重写equals和hashCode的引用对象进行去重

在日常的Java开发中,我们经常会使用Set集合来实现去重操作,确保集合中不含有重复的元素。然而,如果使用未重写equals()和hashCode()方法的引用对象进行去重,可能会导致意外的行为,最近了在项目中就遇到了这个情况,让我们深入探讨这个问题,并引以为戒,确保正确实现去重操作。

先看有问题的代码

代码中去重

  List<UrlEntity> twoList= getSame();
  Set<UrlEntity> set = new HashSet<UrlEntity>();
    //对list中的UrlEntity去重
  set.addAll(twoList);

实体类:UrlEntity

import java.util.HashSet;
import java.util.Set;

public class UrlEntity {
    private Integer id;
    private String url;


    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public UrlEntity(Integer id, String url) {
        this.id = id;
        this.url = url;
    }

    public static void main(String[] args) {
        UrlEntity entity1 = new UrlEntity(1"test");
        UrlEntity entity2 = new UrlEntity(1"test");
        Set<UrlEntity> set = new HashSet<>();
        set.add(entity1);
        set.add(entity2);
        System.out.println(set);
    }
}

输出结果:

[cn.xj.javautil.collection.UrlEntity@7c53a9eb, cn.xj.javautil.collection.UrlEntity@ed17bee]

可以看到,这样并未得到我们想要的去重效果

了解Set集合去重原理:

  • Set是Java中的一种无序集合,不允许包含重复元素。

实际上,HashSet是对HashMap的一个包装,它使用HashMap的键作为集合中的元素,并将HashMap的值设置为一个固定的对象(在实现中称为PRESENT)。

当你向HashSet中添加一个元素时,实际上是将该元素作为HashMap的键,并将对应的值设置为PRESENT对象。HashSet在内部使用一个HashMap来存储元素,每个键值对中的键对应于集合中的元素,而值则是一个共享的PRESENT对象。由于HashMap的键是唯一的,所以在HashSet中也不会出现重复的元素,从而实现了集合的去重功能。HashSet add源码

    public boolean add(E e) {
        return map.put(e, PRESENT)==null;
    }
  • Set的去重原理是基于元素的hashCode()和equals()方法。通过计算元素的哈希码(hashCode())和比较元素的内容(equals()),Set判断元素是否相等,避免添加重复元素。

HashMap put()源码

    /**
     * ASSOciates the specified value with the specified key in this map.
     * If the map previously contained a mapping for the key, the old
     * value is replaced.
     *
     * @param key key with which the specified value is to be associated
     * @param value value to be associated with the specified key
     * @return the previous value associated with <tt>key</tt>, or
     *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
     *         (A <tt>null</tt> return can also indicate that the map
     *         previously associated <tt>null</tt> with <tt>key</tt>.)
     */
    public V put(K key, V value) {
        return putVal(hash(key), key, value, falsetrue);
    }

    /**
     * Implements Map.put and related methods.
     *
     * @param hash hash for key
     * @param key the key
     * @param value the value to put
     * @param onlyIfAbsent if true, don't change existing value
     * @param evict if false, the table is in creation mode.
     * @return previous value, or null if none
     */
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

这段代码展示了 HashMap 中键值对插入的过程,包括处理哈希冲突、链表转换为红黑树等情况,还是有点复杂的,感兴趣的小伙伴可以仔细研究下。但是我们可以看到,他对是通过计算key的哈希码(hashCode())和比较key的内容(equals())判断key是否相等的。

问题所在:未重写equals和hashCode方法的引用对象

  • 引用对象在Java中默认是根据内存地址进行比较的。

Object equals 源码

    public boolean equals(Object obj) {
        return (this == obj);
    }
  • 如果引用对象没有重新实现equals()和hashCode()方法,它们的比较行为将根据默认的Object类实现。
  • 默认的equals()方法是使用==操作符进行引用地址比较,hashCode()方法是根据内存地址计算的哈希码。
  • 这样的行为可能导致Set集合无法正确去重,即使两个对象的内容完全相同,也可能被当作不同的元素存储在Set中。

解决方案:正确实现equals和hashCode方法

  • 在自定义的引用对象中,根据对象的内容重写equals()方法,确保比较的是对象的属性值是否相等。
  • 重写hashCode()方法,根据对象的属性值来计算哈希码,保证具有相同内容的对象具有相同的哈希码。

重新后的实体类

import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

public class UrlEntity {
    private Integer id;
    private String url;


    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public UrlEntity(Integer id, String url) {
        this.id = id;
        this.url = url;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        UrlEntity entity = (UrlEntity) o;
        return Objects.equals(id, entity.id) && Objects.equals(url, entity.url);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, url);
    }

    public static void main(String[] args) {
        UrlEntity entity1 = new UrlEntity(1"test");
        UrlEntity entity2 = new UrlEntity(1"test");
        Set<UrlEntity> set = new HashSet<>();
        set.add(entity1);
        set.add(entity2);
        entity1.equals(entity2);
        System.out.println(set);
    }
}

输出结果:

[cn.xj.javautil.collection.UrlEntity@364872]

我们可以看到已经达到我们去重的目的了,如果我们要根据实体类的一个或特定的几个属性来判断对象是否相等,我们equals()和hashCode()的方法只选择特定的属性即可。

总结

  • 使用Set集合进行去重是一个常见的操作,但必须谨慎处理引用对象的去重。
  • 未重写equals()和hashCode()方法可能导致意外的去重行为,集合中可能包含相同内容但被认为不同的对象。
  • 正确实现equals()和hashCode()方法是确保Set集合正确去重的关键。
  • 引以为戒,避免在Set中使用未重写equals()和hashCode()方法的引用对象进行去重,以确保代码的正确性和稳定性。

通过以上文章,希望读者朋友们能够深刻理解Set集合去重原理,并意识到在使用Set集合进行去重时,正确实现equals()和hashCode()方法的重要性,以避免不必要的错误和问题。


原文始发于微信公众号(修己xj):引以为戒:避免在Set中使用未重写equals和hashCode的引用对象进行去重

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/168536.html

(0)
小半的头像小半

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!