【问题标题】:getting duplicate values in a Set of tuples在一组元组中获取重复值
【发布时间】:2013-11-10 00:55:27
【问题描述】:

我正在尝试在 Java 中为整数元组创建一个 Set。

例如:

class Tuple
{
    int first;
    int second;
    public Tuple(int i, int j)
    {
        this.first=i;
        this.second=j;
    }
}

然后尝试像这样填充一个集合:

Set pairs = new HashSet<Tuple>();
pairs.add(new Tuple(1,2));
pairs.add(new Tuple(1,2));
pairs.add(new Tuple(1,2));

对于一些元组对象。但我仍然得到重复:

System.out.println("Size: " + pairs.size());
for (Tuple t : (HashSet<Tuple>) pairs) {
    System.out.println(t.toString());
}

任何人都可以帮助摆脱重复吗?

【问题讨论】:

  • 您认为如何发现重复项?

标签: java collections set


【解决方案1】:

覆盖hashCode()equals() 方法。

当你想说两个对象相等时,它们的 hashCodes 需要以返回相同值且equals() 将返回 true 的方式实现。当我们尝试将一个对象插入哈希数据结构时,它首先调用该对象上的hashCode(),然后调用equals()方法,集合中的对象与该对象具有相同的哈希码。

我假设你只想要一个Tuple 对象HashSet。按如下方式更改您的班级:

public class Tuple {
    int first;
    int second;
    public Tuple(int i, int j){
        this.first=i;
        this.second=j;
    }
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + first;
        result = prime * result + second;
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Tuple other = (Tuple) obj;
        if (first != other.first)
            return false;
        if (second != other.second)
            return false;
        return true;
    }     
}

【讨论】:

    【解决方案2】:

    Tuple 必须实现 hashCodeequals 才能在 HashSet 中工作。

    【讨论】:

      猜你喜欢
      • 2016-03-06
      • 2023-03-21
      • 2011-11-14
      • 2021-07-04
      • 1970-01-01
      • 1970-01-01
      • 2011-03-09
      • 1970-01-01
      • 2021-01-19
      相关资源
      最近更新 更多