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>
What happens if we put a key object in a HashMap which exists? Explanation: HashMap always contains unique keys. If same key is inserted again, the new object replaces the previous object.
Answer to your question is yes, objects of custom classes can be used as a key in a HashMap.
Duplicates: HashSet doesn't allow duplicate values. HashMap stores key, value pairs and it does not allow duplicate keys. If the key is duplicate then the old key is replaced with the new value.
The behavior of a map is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is a key in the map. You simply shouldn't mutate keys (in the way which changes their "hashCode"/"equals"). You will definitely have very long and awful debugging if you try.
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).
Effective Java - Methods common to all objects
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With