[英]Equals method used in Map key comaprison
我知道,當有人在子類中添加新方面時,無法擴展覆蓋方法equals()
並使其保持“保留”狀態。 Point
類及其子類的常見示例對其進行了演示:
public class Point {
Double d1;
Double d2;
public Point(double d1, double d2){
this.d1 = d1;
this.d2 = d2;
}
}
public class ColorPoint extends Point {
String color;
public ColorPoint(double d1, double d2, String s) {
super(d1, d2);
color = s;
}
}
如果我們有Eclipse創建方法equals()
和hashCode()
,則在ColorPoint
的情況下還考慮了color屬性。 因此,證明equals()
方法不對稱。 編碼:
Point p1 = new Point(2,2);
ColorPoint cp1 = new ColorPoint(2, 2, "blue");
System.out.println(p1.equals(cp1));
System.out.println(cp1.equals(p1));
打印:
真假
同樣可以證明該方法不是傳遞性的。 但是,當我將對象作為HasMap
鍵傳遞時,無論我傳遞它們的順序HasMap
,它都會將它們識別為不同的鍵。 編碼:
Point p1 = new Point(2,2);
Point p2 = new Point(3.1,3.1);
ColorPoint cp1 = new ColorPoint(2, 2, "blue");
ColorPoint cp2 = new ColorPoint(3.1,3.1, "red");
Map<Point, Integer> map = new HashMap<>();
map.put(cp2, 4); map.put(cp1, 3);
map.put(p1, 1); map.put(p2, 2);
System.out.println(map.size());
即使我以其他順序傳遞對象,也總是打印4。 那是預期的嗎? 那么, Map
使用哪種方法比較鍵?
這可能是因為eclipse生成的hashcode()考慮了ColourPoint的顏色字段,因此這些點和顏色點會散列到不同的存儲桶中,並且永遠不會與equals()進行比較。
請注意,這意味着hashcode()的約定已損壞-兩個對象的a.equals(b)== true正在生成不同的哈希碼。 基本上,不要這樣做!
Scala語言對此感興趣,使用canEqual方法確定兩個對象是否相等。 在這里查看 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.