我有一个TreeMap,其中RobotKey是一个由字符串字段域和长字段时间戳组成的类.RobotKey实现如下可比:
@Override
public boolean equals(Object obj) {
if (this.domain.equals(((RobotKey) obj).getDomain()))
return true;
return false;
}
Run Code Online (Sandbox Code Playgroud)
树图根据以下compareTo函数排序:
@Override
public int compareTo(RobotKey arg0) {
if (this.lastAccessed < arg0.lastAccessed)
return -1;
else if (this.domain.equals(arg0.getDomain()))
return 0;
else
return 1;
}
Run Code Online (Sandbox Code Playgroud)
所以基本上,地图是通过域名访问的,并根据时间戳进行排序.
我做了treemap.get(RobotKey e),其中e与treemap中的现有条目具有相同的域名,但具有不同的时间戳.这应该返回正确的RobotValue,因为Map操作是用equals完成的.但它反而返回null表示找不到RobotKey.知道为什么会这样吗?我做错了什么,我该如何解决?谢谢!
问题是你的equals和compareTo方法的不一致.在compareTo必须返回0,当且仅当equals返回true,据我记得TreeMap的(或TreeSet中)不调用equals方法,它只是使用compareTo其结果表明重复键.
| 归档时间: |
|
| 查看次数: |
3239 次 |
| 最近记录: |