Reputation: 1359
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...
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);
}
Upvotes: 0
Views: 743
Reputation: 5565
Have you implemented hashCode and equals for Key and BasicRectangleCollection?
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.
Upvotes: 1