Java Set 集合 - 覆盖 equals 方法

2022-01-17 00:00:00 set equals overriding java

有没有办法覆盖 Set 数据类型使用的 equals 方法?我为一个名为Fee 的类编写了一个自定义equals 方法.现在我有一个 FeeLnkedList 并且我想确保没有重复的条目.因此,我正在考虑使用 LinkedListSet,但决定两个费用是否相等的标准存在于重写的 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();
  }

}

相关文章