2017-08-28 63 views
1

我想定義一個Pair類,其中< 2,3>和< 3,2>是同一件事。平等的方法被覆蓋,但我不知道如何重寫hashcode函數來匹配。我到目前爲止的代碼是:雙對象重寫等於使反向對也相同

Set<Pair> edgePairs=new HashSet<>(); 

    edgePairs.add(new Pair(2,3)); 
    edgePairs.add(new Pair(2,4)); 
    edgePairs.add(new Pair(2,5)); 
    edgePairs.add(new Pair(4,2)); 
    edgePairs.add(new Pair(2,3)); 
    edgePairs.add(new Pair(3,2)); 

    for (Pair edgePair : edgePairs) { 
     System.out.println(edgePair.x+" "+edgePair.y); 
    } 

輸出:

2 3 
2 4 
2 5 
4 2 
3 2 

正確的輸出不應該包含對< 4,2>和< 3,2>

對類:

public class Pair 
{ 
    int x, y; 

    public Pair(int x, int y) { 
     this.x = x; this.y = y; 
    } 

    @Override 
    public boolean equals(Object o) { 
     if (this == o) return true; 
     if (o == null || getClass() != o.getClass()) return false; 
     Pair that = (Pair) o; 
     if ((x == that.y && y == that.x)||(x == that.x && y == that.y))     
       return true; 

     return false; 
    } 

    @Override 
    public int hashCode() { 
     int result = x; result = 31 * result + y; 
     return result; 
    } 
} 
+2

您的代碼看起來不正確。如果兩個對象之間的equals爲真,請確保哈希碼總是返回相同的結果。 – dabaicai

回答

2

如果您只是讓您的hashCode返回x + y,它們中的任何一個都不乘以31,那麼參數的順序就不重要了。

+3

這會導致很多散列衝突。考慮2 + 7,將導致與3 + 6和4 + 5以及1 + 8和0 + 9相同的哈希碼。 – bhspencer

+0

[HashSet](http://grepcode.com/file/repository.grepcode.com/java /root/jdk/openjdk/6-b14/java/util/AbstractSet.java#AbstractSet.hashCode%28%29)'shashCode'的實現在這裏很有幫助;他們會總結x和y的_hashcodes_。 –

+1

@AndrewRueckert這沒什麼區別,因爲'Integer'類的'hashCode'實現只是爲了返回值。 –

0

你是真的很近,你只需要進行哈希函數更具體

@Override 
public int hashCode() { 
    int a = 0, b = 0; 
    if (x > y) { 
     a = x; 
     b = y 
    } else { 
     a = y; 
     b = x; 
    } 
    int result = a; result = 31 * result + b; 
    return result; 
} 

或者你可以重做Pair類並進行x和y的升序存儲。

無論使用哪種方法,您都需要將散列公式中變量的順序與變量輸入的順序分開。