简体   繁体   English

通过哈希图中的键获取值返回null

[英]Getting value by key in hashmap returns null

I'm trying to store a collection of BasicRectangle objects in a hashmap (which is contained in the class BasicRectangleCollection. The key is an object containing the integer fields x and y. I'm then using the method "find" to retrieve it, which simply takes the x and y values and turns them into a Key object. However, when I run "find" then it returns null and I don't understand why this would happen when the object I'm looking for is most definitely present... 我试图将一个BasicRectangle对象的集合存储在一个哈希图中(包含在BasicRectangleCollection类中。该键是一个包含整数字段x和y的对象。然后,我使用“ find”方法来检索它,它只接受x和y值并将其转换为Key对象。但是,当我运行“ find”时,它将返回null,我不明白为什么当我要找的对象绝对存在时会发生这种情况...

Relevant code: 相关代码:

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);
}

Have you implemented hashCode and equals for Key and BasicRectangleCollection? 您是否实现了Key和BasicRectangleCollection的hashCode等于?

If not, I think Java uses the objects reference in memory as the hashcode which means that unless two objects are the same instance they are not equal and your search will not work as desired. 如果不是这样,我认为Java将内存中的对象引用用作哈希码,这意味着除非两个对象是同一实例,否则它们将不相等,并且您的搜索将无法正常进行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM