Reputation: 798
I'm trying to use a HashMap with my class Cell as the key. However, after putting an item into the HashMap, calling contains on the item will return false.
public static void main(String args[]) {
HashMap<Cell, String> map = new HashMap<Cell, String>();
map.put(new Cell(0,0), "Bob");
System.out.println(map.containsKey(new Cell(0,0)));
System.out.println(new Cell(0,0).equals(new Cell(0,0)));
}
This prints out false and true, where it should print true and true, since according to the Map docs containsKey uses .equals(). What am I doing wrong?
Upvotes: 2
Views: 2918
Reputation: 2043
This is most likely because you don't have equals()
and hashCode()
implemented. In Java, the rule of thumb is that if you implement one, you must implement the other. In your case, it's mandatory because HashMap
makes use of them.
You created two separate objects with two separate addresses. Without these methods, the JVM has no way of knowing that the objects are "the same."
See http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#hashCode()
Upvotes: 4
Reputation: 20129
You likely forgot to implement the hashcode()
function for Cell
, which is also required in order to use a user defined class in a HashMap
. Here is a simple and generally accurate way to implement a hashcode()
function:
int hashcode(){
return (field1.toString()+field2.toString()+...+fieldN.toString()).hashcode();
}
Where field1
to fieldN
are the fields in your class. If the fields are primatives (ie int
) just take out the toString()
.
Upvotes: 0
Reputation: 1990
calling new Cell(0,0) several times produce different objects with different hash Codes. You should implement hashCode for Cell class.
Upvotes: 0
Reputation: 279960
Consider how a HashMap
is implemented. When putting, it first calculates the object hashCode()
to figure out which bucket to place the object in. When it tries to retrieve an object, it again gets its hashCode()
, identifies to target bucket, goes through the linked list in the bucket, calling equals()
against each object. It returns if it finds a match.
In other words, when you use HashMap
you need to have a correct and matching implementation of equals()
and hashCode()
.
The default hashCode()
method inherited from Object
does not correctly return the same hashCode()
unless the object references are the same. In your case they are not.
Upvotes: 1