所以,我用 Java 编写了这段代码:
import java.util.HashSet;
class Interval{
long from;
long to;
public Interval(long from, long to) {
this.from = from;
this.to = to;
}
public boolean equals(Interval other) {
return from == other.from && to == other.to;
}
}
public class Test {
public static void main(String[] args) {
HashSet<Interval> mySet = new HashSet<Interval>();
mySet.add(new Interval(1,2));
mySet.add(new Interval(1,2));
for(Interval in : mySet) {
System.out.println(in.from + " " + in.to);
}
}
}
问题是集合无法识别已经存在从 1 到 2 的区间。我定义了函数 equals,但它仍然不起作用。我尝试实现 Comparable 接口(interface)并重载compareTo 函数,但还是一无所获。有人可以告诉我如何解决这个问题吗?
谢谢!
最佳答案
您需要从 java.lang.Object
重写 equals
。
您没有,因为您的不接受对象作为参数。
public boolean equals(Object obj) {
if (obj == null)
return false;
else if (this.getClass() != obj.getClass())
return false;
else {
Interval other = (Interval) obj;
return from == other.from && to == other.to;
}
}
对于 hashCode,您可以这样做。
public int hashCode() {
return new Long(this.from).hashCode();
}
所以总的来说,你得到了这段代码。
import java.util.HashSet;
class Interval {
long from;
long to;
public Interval(long from, long to) {
this.from = from;
this.to = to;
}
public boolean equals(Object obj) {
if (obj == null)
return false;
else if (this.getClass() != obj.getClass())
return false;
else {
Interval other = (Interval) obj;
return from == other.from && to == other.to;
}
}
public int hashCode() {
return new Long(this.from).hashCode();
}
}
public class Test003 {
public static void main(String[] args) {
HashSet<Interval> mySet = new HashSet<Interval>();
mySet.add(new Interval(1, 2));
mySet.add(new Interval2(1, 2));
for (Interval in : mySet) {
System.out.println(in.from + " " + in.to);
}
}
}
关于java - 识别 HashSet 中的重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21237270/