所以,我有这个用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的间隔。我将函数定义为等于,但它仍然不起作用。我尝试实现Comparable接口并重载compareTo函数,但同样没有。有人能告诉我怎样才能解决这个问题?
谢谢!
答案 0 :(得分:2)
您需要从equals
覆盖java.lang.Object
。
你没有,因为你不接受Object作为参数。
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);
}
}
}
答案 1 :(得分:1)
使用如下所示的equals和hashCode方法,它可以正常工作
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (from ^ from >>> 32);
result = prime * result + (int) (to ^ to >>> 32);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Interval other = (Interval) obj;
if (from != other.from) {
return false;
}
if (to != other.to) {
return false;
}
return true;
}