Java 在hashmap中按键获取值返回null
我试图将BasicRectangle对象的集合存储在hashmap(包含在类BasicRectangleCollection中)中。键是一个包含整数字段x和y的对象。 然后我使用方法“find”来检索它,它只需要获取x和y值并将它们转换为一个键对象。然而,当我运行“find”时,它会返回null,我不明白为什么在我查找的对象最确定存在时会发生这种情况 相关代码:Java 在hashmap中按键获取值返回null,java,null,hashmap,Java,Null,Hashmap,我试图将BasicRectangle对象的集合存储在hashmap(包含在类BasicRectangleCollection中)中。键是一个包含整数字段x和y的对象。 然后我使用方法“find”来检索它,它只需要获取x和y值并将它们转换为一个键对象。然而,当我运行“find”时,它会返回null,我不明白为什么在我查找的对象最确定存在时会发生这种情况 相关代码: HashMap<Key,BasicRectangle> rectangles; public BasicRectangl
HashMap<Key,BasicRectangle> rectangles;
public BasicRectangleCollection(BasicRectangle bRect){
this.rectangles = new HashMap<>();
int x = bRect.getX();
int y = bRect.getY();
rectangles.put(new Key(x,y), bRect);
}
@Override
public BasicRectangle find(int x, int y) {
return rectangles.get(new Key(x,y));
}
public static void main(String[] args) {
BasicRectangle rectangle= new BasicRectangle(0,0,5,5);
BasicRectangleCollection collection = new BasicRectangleCollection(rectangle);
BasicRectangle found = collection.find(0,0);
System.out.println(found);
}
HashMap矩形;
公共BasicRectangle集合(BasicRectangle bRect){
this.rectangles=newhashmap();
intx=bRect.getX();
int y=bRect.getY();
矩形。put(新键(x,y),bRect);
}
@凌驾
公共基本角查找(整数x,整数y){
返回矩形。get(新键(x,y));
}
公共静态void main(字符串[]args){
BasicRectangle矩形=新的BasicRectangle(0,0,5,5);
BasicRectangleCollection集合=新的BasicRectangleCollection(矩形);
BasicRectangle found=collection.find(0,0);
System.out.println(已找到);
}
您是否为Key和BasicRectangleCollection实现了hashCode和equals
如果不是,我认为Java使用内存中的对象引用作为哈希代码,这意味着除非两个对象是同一个实例,否则它们是不相等的,您的搜索将无法按预期工作。Key和
BasicRectangle
类是否正确地实现了equals和hashcode?然而,您没有感觉到共享Key.equals()
和Key.hashCode()
与我们一起实现是很重要的。@JigarJoshiBasicRectangle
在这里不需要这些实现,只需要Key
.Definitive(参见OP在回答中的注释)重复的啊,呃,不-我没有红脸。我假设它会继承一个合适的实现。谢谢你的解释,我现在就去实现它……口哨问题,伙计!别难过,我们都做了;-)。你认为你也可以点击绿色的复选标记,这样我就可以得到一些额外的分数吗?当然,我只是在等待计时器允许我:)。再次感谢:)。没问题,好好吃一顿,坚持下去!提高编程水平的最佳方法是……嗯……编程:-),通常,这里的人都会提供帮助。我相信有一天你也会回馈的。BasicRectangleCollection不需要实现equals和hashCode。只有钥匙可以。