2014-01-31 36 views
1

我不明白爲什麼包含()的HashSet的在下面的示例返回假:套裝包括和對象等於

import java.util.HashSet; 
import java.util.Set; 

public class MyMatching { 

    private Integer[] id; 

    public MyMatching(Integer id1, Integer id2) { 
     this.id = new Integer[2]; 
     id[0] = id1; 
     id[1] = id2; 
    } 

    public String getId() { 
     return id[0] + ":" + id[1]; 
    } 

    @Override 
    public boolean equals(Object other) { 
     if (this == other) 
      return true; 
     if (other == null || (this.getClass() != other.getClass())) { 
      return false; 
     } 
     MyMatching otherMatching = (MyMatching) other; 
     return (getId().equals(otherMatching.getId())); 
    } 

    @Override 
    public int hashCode() { 
     int result = 31 * id.hashCode(); 
     return result; 
    } 

    public static void main(String[] args) { 
     MyMatching matching1 = new MyMatching(1571021585, 848339230); 
     MyMatching matching2 = new MyMatching(661883516, 310961952); 
     Set<MyMatching> matchings = new HashSet<>(); 
     matchings.add(matching1); 
     matchings.add(matching2); 

     MyMatching testMatching = new MyMatching(1571021585, 848339230); 
     System.out.print("HashSet contains testMatching: "); 
     System.out.println(matchings.contains(testMatching)); 

     Object[] matchingsArray = matchings.toArray(); 
     for (Object o : matchingsArray) { 
      System.out.print("Object equals testMatching: "); 
      System.out.println(o.equals(testMatching)); 
     } 
    } 
} 

結果是:

HashSet contains testMatching: false 
Object equals testMatching: false 
Object equals testMatching: true 

Set's contain method的文檔:

如果此集合包含指定的元素,則返回true。更正式地說,如果>且只有當這個集合包含一個元素e(例如(o == null?e == null:o.equals(e))時才返回true。

我的問題:爲什麼contains()在Set上返回false,但equals()在對象上返回true?

+0

啊,這很清楚。我不得不睜開眼睛...... :) 感謝您的提示! – rch

+0

我錯了我的朋友,抱歉誤導你。忽略我最後的評論。 – Maroun

回答

6

hashCode的實現與equals不一致:id是一個數組,它不基於數組中保存的值計算哈希代碼。

對於正確執行,你可以返回生成的ID字符串代替的哈希碼:與

@Override 
public int hashCode() { 
    return getId().hashCode(); 
} 

或者你也可以直接計算基於陣列值的哈希碼,例如:

@Override 
public int hashCode() { 
    return id[0]^id[1]; 
} 
+0

但仍然..他不應該使用'contains'來檢查'HashSet'是否包含另一個'HashSet'。或者我在這裏錯過了什麼? – Maroun

+0

@ᴍarounᴍaroun這是在哪裏? –

+0

我誤解了他的代碼,對於混淆抱歉。 – Maroun