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

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

先看有问题的代码

代码中去重

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

实体类:UrlEntity

typescript 复制代码
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);
    }
}

输出结果:

kotlin 复制代码
[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源码

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

HashMap put()源码

scss 复制代码
    /**
     * 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, false, true);
    }

    /**
     * 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 源码

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

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

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

重新后的实体类

typescript 复制代码
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);
    }
}

输出结果:

csharp 复制代码
[cn.xj.javautil.collection.UrlEntity@364872]

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

总结

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

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

相关推荐
追逐时光者2 小时前
推荐 12 款开源美观、简单易用的 WPF UI 控件库,让 WPF 应用界面焕然一新!
后端·.net
Jagger_2 小时前
敏捷开发流程-精简版
前端·后端
苏打水com3 小时前
数据库进阶实战:从性能优化到分布式架构的核心突破
数据库·后端
间彧4 小时前
Spring Cloud Gateway与Kong或Nginx等API网关相比有哪些优劣势?
后端
间彧4 小时前
如何基于Spring Cloud Gateway实现灰度发布的具体配置示例?
后端
间彧4 小时前
在实际项目中如何设计一个高可用的Spring Cloud Gateway集群?
后端
间彧4 小时前
如何为Spring Cloud Gateway配置具体的负载均衡策略?
后端
间彧4 小时前
Spring Cloud Gateway详解与应用实战
后端
EnCi Zheng6 小时前
SpringBoot 配置文件完全指南-从入门到精通
java·spring boot·后端
烙印6016 小时前
Spring容器的心脏:深度解析refresh()方法(上)
java·后端·spring