字典Java从ConcurrentHashMap中的等效键获取值
对于此代码:
//...
System.out.println(Main.getCurrentPage().getDots()); //Type: ConcurrentHashMap<Point,String>
System.out.println(mdp.getActivePoint()); //Type: Point
System.out.println(Main.getRealCurrentPage().getDots().get(mdp.getActivePoint())); //Type: String
//...
我得到这个输出:
{java.awt.Point[x=278,y=354]=A1, java.awt.Point[x=542,y=370]=A1}
java.awt.Point[x=278,y=354]
null
我不明白为什么这个输出的第三行不是
A1
因为输出的第二行中打印的点包含在地图的键集中
我认为这是因为出于某种原因,它们没有被视为同一个对象/引用,所以我创建了一个扩展ConcurrentHashMap的类:
public class GoodCHashMap<K,V> extends ConcurrentHashMap<K,V>{
public GoodCHashMap(){
super();
}
public GoodCHashMap(GoodCHashMap<K,V> m){
super(m);
}
@Override
public V get(Object key){
if(key instanceof Point){
//System.out.println("!!!! hit");
Point point = (Point) key;
for(Object o : keySet()){
Point p = (Point) o;
if(point.x == p.x && point.y == p.y){
//System.out.println("This was a thing");
return super.get(p);
}
}
return null;
}else{
return super.get(key);
}
}
}
这样设计的目的是,如果一个点被传递到get方法中,它会遍历自己的键集,如果那里的一个点与参数具有相同的坐标,它会在默认的ConcurrentHashMap get方法中使用键集中的点。然而,这也失败了
有人能帮我理解并克服这种行为吗
共 (0) 个答案