HashMap <String, Object>: how to put the object itself as instead of String

A a = new A(); //classA { } HashMap<String, Object> hm = new Hashmap<String,Object>(); hm.put("A", a); 

My question is: how can I put the object itself instead of "A" in the same declaration?

 hm.put(`a??`, a); 
+4
source share
5 answers

You simply cannot do this; language forbids it. This is only possible if your class A is a subclass of String , which is not possible since String declared as final in Java.

Regarding your interview question: This is not possible because of the generic type parameter that was selected for the announcement. You can learn more about this in the Restricted Type Parameters .

+3
source

If the class contained an immutable decent String field, you could use it.

 // the id property must be a String, immutable and unique for each instance! myMap.put(a.getId(), a); 
0
source

If you want to make any object as a key in the HashMap , then this object must be immutable .. Because you do not want anyone to change your key after adding them to the HashMap ..

Just imagine if your keys are changed after insertion, you can never find your inserted value.

But if your key is immutable , then if someone tries to change your keys, he will actually create a new one for himself, but you will still have your own.

This is what happens if you use String as your key in a HashMap (they cannot be changed). So, if you want your object to be the key, either you make your class a subclass of String (which you cannot do), or just make your class immutable ..

0
source
 A a = new A(); //classA { } Map<A, A> hm = new Hashmap<A, A>(); hm.put(a, a); 

But I see no reason to invest a->a

0
source

This is really possible with a raw type , for example:

 Object key = ...; Object value = ...; Map<String, Integer> map = new HashMap<>();//a normal map Map rawMap = map; // here is the raw type rawMap.put(key, value); // it works! 

This is normal, but problems arise when you try to use a shared card later:

 Integer value = map.get(key);// ClassCastException (unless value actually is an Integer) 

That's why they told you that this is a "dirty trick." You should not use it.

0
source

Source: https://habr.com/ru/post/1437067/


All Articles