Using an instance of an object as a key in hashmap, and then access it with exactly new object? [duplicate]
You need to implement hashCode
and equals
on Key
. The default implementation of these methods simply checks for instance equality (in other words, two Object
s will only be equal if they are in fact the same object).
Further reading
Effective Java - Methods common to all objects
Your problem is likely that Key
did not implement hashCode()
and equals()
correctly (or at all). In order to be used as a HashMap
key the class has to implement these two methods to reflect "equality" of two objects.
If you create two different instances with
Key a = new Key("xyz");
Key b = new Key("xyz");
and expect them to be equal and work in a HashMap
, you have to override hashCode()
so that it returns the same value in both instances, and equals()
returns true when comparing them.
If the object identity is based on the string value, then
@Override
public int hashCode()
{
return theStringValue.hashCode();
}
and
@Override
public boolean equals(Object o)
{
return this.theStringValue.equals(o);
}
should work
When a class does not override the equals()
or hashCode()
methods, the default implementations found on the Object
class are used instead. In particular, equals()
simply does a check for reference equality.
That immediately explains why your approach isn't working: the new Key
object clearly isn't referring to the old Key
object.
If you'd like to be able to specify a new instance with the same property, then you should override the equals()
method with an implementation that meets your criteria for key equality. You should override hashCode()
as well, to have full control over the key comparison process.