Java Set集合 - 覆盖equals方法 [英] Java Set collection - override equals method

查看:169
本文介绍了Java Set集合 - 覆盖equals方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法覆盖 Set 数据类型使用的 equals 方法?我为一个名为 Fee 的类编写了一个自定义等于的方法。现在我有一个 LnkedList 费用,我想确保没有重复的条目。因此,我正在考虑使用 Set 设置 LinkedList ,但决定两项费用是否相等的标准存在于费用类中的覆盖等于方法。

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 ,我将不得不迭代每个列表项并在<$中调用overriden equals 方法c $ c>费用类,其余条目作为参数。仅仅阅读这个听起来就像处理太多会增加计算复杂性。

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.

我可以使用设置重写等于方法?我应该吗?

Can I use Set with an overridden equals method? Should I?

推荐答案

正如杰夫福斯特所说:


Set.equals()方法仅用于比较两个集合是否相等。

The Set.equals() method is only used to compare two sets for equality.

您可以使用设置以删除重复的条目,但要注意: HashSet 不使用等于()包含对象的方法以确定相等。

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.

A HashSet 带有内部 HashMap <整数(HashCode),对象> 条目并使用equals()以及equals方法 HashCode 以确定相等。

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.

解决此问题的一种方法是覆盖 hashCode()在您放入Set的类中,以便它代表您的 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方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆