Re: Integer as key in HashMap
Ike wrote:
if I have an Integer object as a key in a HashMap, and I create that Integer
from an int, use that to put() a String as value in the HashMap, can I later
create a new Integer object, from the same int value, and use this latter
Integer object to get() the value of that String I put in?
Or must I use the actual Integer object I first created? Thank you, Ike
It will work the first way.
In general, you need to consider the equals method for the key class. An
Object, or any object inheriting the Object equals, is equal to itself
and nothing else. For an Object key, you would have to use the actual
Object instance.
The Integer equals API documentation says "The result is true if and
only if the argument is not null and is an Integer object that contains
the same int value as this object.". If you follow the procedure you
describe, the object used in get() will be equal to the key, so the
second method works.
If you don't trust the implementer of the key class, you should also
check the hashCode description. The first method is reliable if, and
only if, the hashCode implementation is consistent with equals according
to the contract described for Object. If two objects are equal, they
must have the same hashCode.
I have not yet found a Sun API class with a problem in this area, and
the Integer documentation says "a hash code value for this object, equal
to the primitive int value represented by this Integer object." which is
fine.
Patricia