我知道,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;
}
}
Run Code Online (Sandbox Code Playgroud)
如果我们有Eclipse创建的方法equals()和hashCode(),但考虑到还的情况下,颜色属性ColorPoint.因此,该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));
Run Code Online (Sandbox Code Playgroud)
打印:
真假
以同样的方式可以证明该方法不具有传递性.然而,当我将对象作为键传递给a时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());
Run Code Online (Sandbox Code Playgroud)
即使我以另一个顺序传递对象,也总是打印4.这是预期的吗?那么,Map为了比较密钥,使用哪种方法?
| 归档时间: |
|
| 查看次数: |
1534 次 |
| 最近记录: |