含IntegerProperty字段的类对象作为HashMap键的问题如何解决
问题原因
当前你自动生成的hashCode和equals方法直接操作IntegerProperty实例本身,而JavaFX的SimpleIntegerProperty的默认相等判断比较的是对象内存地址,而非其存储的int数值。你创建的a1和a2两个实例持有的x、y都是独立的IntegerProperty对象,哪怕存储的数值完全一致,两者的哈希值不同、equals判断也会返回false,因此无法通过a2从哈希映射中查询到a1对应的条目。
修复方案
将hashCode和equals的逻辑修改为比较IntegerProperty包裹的int值即可,修改后的代码如下:
@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + getX(); result = prime * result + getY(); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; A other = (A) obj; if (getX() != other.getX()) return false; if (getY() != other.getY()) return false; return true; }
额外提示:你提供的类A代码中构造方法名写为了
Coordinate,和类名不一致,属于笔误,需要修改为public A(int x, int y)才能正常编译。
内容的提问来源于stack exchange,提问作者CoreNoob
相关产品推荐
相关产品推荐

