0

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);
}
The General
  • 1,239
  • 2
  • 17
  • 28
  • 3
    does `Key` and `BasicRectangle` class implement equals and hashcode properly ? – jmj Mar 22 '14 at 00:26
  • And yet, you didn't feel that sharing your `Key.equals()` and `Key.hashCode()` implementations with us was important. – Jason C Mar 22 '14 at 00:29
  • 1
    @JigarJoshi `BasicRectangle` does not need those implementations here, only `Key`. – Jason C Mar 22 '14 at 00:31
  • definite (see OP's comments in answers) duplicate of [Why do I need to override the equals and hashCode methods in Java?](http://stackoverflow.com/questions/2265503/why-do-i-need-to-override-the-equals-and-hashcode-methods-in-java) – Jason C Mar 22 '14 at 00:32

1 Answers1

1

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.

Reuben Tanner
  • 5,229
  • 3
  • 31
  • 46
  • ah, erm, no - I didn't *redface*. I assumed that it would inherit a suitable implementation. Thank you for your explanation, I'll go implement that now.... *whistles* – The General Mar 22 '14 at 00:35
  • Sure thing dude! Don't feel bad though, we've all done it ;-). Do you think you could click the green check mark as well so I can get some extra points? – Reuben Tanner Mar 22 '14 at 00:40
  • Sure, I was just waiting for the timer to allow me to :). Thanks again :). – The General Mar 22 '14 at 00:42
  • No problem, have a good one and keep at it! The best way to get better at programming is...well...to program :-) and, usually, people on here are helpful. I'm sure some day you'll be giving back too. – Reuben Tanner Mar 22 '14 at 00:42
  • BasicRectangleCollection doesn't need to implement equals and hashCode. Only Key does. – user253751 Mar 22 '14 at 02:21