为什么我得到以下代码的输出 2 而不是 1? HashSet 不允许重复元素。
import java.util.*;
import java.io.*;
import java.math.*;
public class Main1
{
static class pair
{
int x;
int y;
public pair (int k, int p)
{
x = k;
y = p;
}
}
public static void main(String[] args)throws IOException
{
Set<pair> hs=new HashSet<pair>();
hs.add(new pair(1,2));
hs.add(new pair(1,2));
System.out.println(hs.size());
}
}
最佳答案
您必须覆盖equals
和hashcode
。
来自Java的Set
接口(interface)的文档:
A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element.
请注意,以下内容将打印 false:
pair p1 = new pair(1, 2);
pair p2 = new pair(1, 2);
System.out.println(p1.equals(p2));
另请注意,java 约定是类名以大写字母开头。
这将为您完成工作:
class Pair {
int x;
int y;
public pair(int k, int p) {
x = k;
y = p;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
pair pair = (pair) o;
return x == pair.x && y == pair.y;
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
}
关于java - java HashSet 中的歧义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50785807/