问题
I have a hasmap with a key object,
HashMap<Key, Object> test;
and make new Key("the same") as key..
so its like..:
test.put(new Key("the same"), someObject);
(without storing that key in a variable)
so.. after a while... i want to access the hashmap, because i do not have the object, i've tried to make new Key("the same") and make it as a key. But it didnt work.
How to make it work? (without saving the first object "key" in a variable)
So meanwhile, for now, im using String object as a key.
HashMap<String, Object>
回答1:
You need to implement hashCode and equals on Key. The default implementation of these methods simply checks for instance equality (in other words, two Objects will only be equal if they are in fact the same object).
Further reading
Effective Java - Methods common to all objects
回答2:
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
回答3:
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.
来源:https://stackoverflow.com/questions/9440380/using-an-instance-of-an-object-as-a-key-in-hashmap-and-then-access-it-with-exac