获取元组集中的重复值

ahs*_*l_k 3 java collections set

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

例如:

class Tuple
{
    int first;
    int second;
    public Tuple(int i, int j)
    {
        this.first=i;
        this.second=j;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后尝试填充这样的集合:

Set pairs = new HashSet<Tuple>();
pairs.add(new Tuple(1,2));
pairs.add(new Tuple(1,2));
pairs.add(new Tuple(1,2));
Run Code Online (Sandbox Code Playgroud)

对于多个元组对象。但我仍然通过以下方式得到重复:

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

任何人都可以帮助删除重复项吗?

Val*_*ade 7

重写hashCode()equals()方法。

当你想说两个对象相等时,它们的 hashCode 需要以返回相同值并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;
    }     
}
Run Code Online (Sandbox Code Playgroud)