Java 获取一组元组中的重复值
我试图用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(
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;
}
}
你认为复制品是如何被发现的?你认为复制品是如何被发现的?