[英]Recognizing duplicates in HashSet
因此,我將這段代碼用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接口並重載compareTo函數,但還是沒有。 有人可以告訴我如何解決這個問題嗎?
謝謝!
您需要從java.lang.Object
重寫equals
。
您沒有,因為您不接受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);
}
}
}
使用下面的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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.