Java 获取一组元组中的重复值

Java 获取一组元组中的重复值,java,collections,set,Java,Collections,Set,我试图用java为整数元组创建一个集合 例如: 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(

我试图用java为整数元组创建一个集合

例如:

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));
Set pairs=new HashSet();
add(新元组(1,2));
add(新元组(1,2));
add(新元组(1,2));
对于许多元组对象。但我还是通过以下方式获得了副本:

System.out.println("Size: " + pairs.size());
for (Tuple t : (HashSet<Tuple>) pairs) {
    System.out.println(t.toString());
}
System.out.println(“大小:+pairs.Size());
对于(元组t:(哈希集)对){
System.out.println(t.toString());
}

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

Tuple
必须实现
hashCode
equals
才能在
HashSet
中工作
Tuple
必须实现
hashCode
equals
才能在
HashSet
中工作
覆盖
hashCode()
equals()
方法

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

我假设在
HashSet
中只需要一个
Tuple
对象。按如下方式更改您的课程:

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;
    }     
}

重写
hashCode()
equals()
方法

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

我假设在
HashSet
中只需要一个
Tuple
对象。按如下方式更改您的课程:

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;
    }     
}

你认为复制品是如何被发现的?你认为复制品是如何被发现的?