我不明白爲什麼包含()的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?
啊,這很清楚。我不得不睜開眼睛...... :) 感謝您的提示! – rch
我錯了我的朋友,抱歉誤導你。忽略我最後的評論。 – Maroun