Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an instance of an object as a key in hashmap, and then access it with exactly new object? [duplicate]

Tags:

java

hashmap

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> 
like image 752
Keenan Gebze Avatar asked Feb 25 '12 01:02

Keenan Gebze


People also ask

What happens when you put a key object in a HashMap that is already present?

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.

Can I use object as a key in HashMap?

Answer to your question is yes, objects of custom classes can be used as a key in a HashMap.

What happens when a duplicate key is put into 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.

What happens if you change an object that was used as a key in a map or set?

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.


1 Answers

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

like image 170
Mark Peters Avatar answered Sep 20 '22 01:09

Mark Peters