HashMap <String, Object>: how to put the object itself as instead of String
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 .
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 ..
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.