Java Set collection - override equals method(Java Set 集合 - 覆盖 equals 方法)
问题描述
有没有办法覆盖 Set
数据类型使用的 equals
方法?我为一个名为Fee
的类编写了一个自定义equals
方法.现在我有一个 Fee
的 LnkedList
并且我想确保没有重复的条目.因此,我正在考虑使用 LinkedList
的 Set
,但决定两个费用是否相等的标准存在于重写的 equals
方法中费用
类.
Is there any way to override the the equals
method used by a Set
datatype? I wrote a custom equals
method for a class called Fee
. Now I have a LnkedList
of Fee
and I want to ensure that there are no duplicated entries. Thus I am considering using a Set
insted of a LinkedList
, but the criteria for deciding if two fees are equal resides in the overriden equals
method in the Fee
class.
如果使用 LinkedList
,我将不得不遍历每个列表项,并在 Fee
类中调用重写的 equals
方法剩余条目作为参数.仅阅读此内容听起来处理量太大,并且会增加计算复杂度.
If using a LinkedList
, I will have to iterate over every list item and call the overriden equals
method in the Fee
class with the remaining entries as a parameter. Just reading this alone sounds like too much processing and will add to computational complexity.
我可以将 Set
与重写的 equals
方法一起使用吗?我应该吗?
Can I use Set
with an overridden equals
method? Should I?
推荐答案
正如 Jeff Foster 所说:
As Jeff Foster said:
Set.equals() 方法仅用于比较两个集合是否相等.
The Set.equals() method is only used to compare two sets for equality.
您可以使用 Set
删除重复的条目,但请注意:HashSet
不使用 equals()
方法其包含的对象来确定相等性.
You can use a Set
to get rid of the duplicate entries, but beware: HashSet
doesn't use the equals()
methods of its containing objects to determine equality.
一个 HashSet
携带一个内部 HashMap
与
条目并使用 equals() 以及HashCode 的 equals 方法来确定相等性.
A HashSet
carries an internal HashMap
with <Integer(HashCode), Object>
entries and uses equals() as well as the equals method of the HashCode to determine equality.
解决问题的一种方法是覆盖您放入 Set 中的 Class 中的 hashCode()
,使其代表您的 equals()
标准
One way to solve the issue is to override hashCode()
in the Class that you put in the Set, so that it represents your equals()
criteria
例如:
class Fee {
String name;
public boolean equals(Object o) {
return (o instanceof Fee) && ((Fee)o.getName()).equals(this.getName());
}
public int hashCode() {
return name.hashCode();
}
}
这篇关于Java Set 集合 - 覆盖 equals 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java Set 集合 - 覆盖 equals 方法


基础教程推荐
- 验证是否调用了所有 getter 方法 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- Java Swing计时器未清除 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 从 python 访问 JVM 2022-01-01