Will the use of Class as key for a HashMap cause undesireable effects

  • A+
Category:Languages

Consider the following:

Map<Class<?>, Object> myMap = new HashMap<Class<?>, Object>(); Foo fooObject = New Foo(); myMap.put(fooObject.getClass(), fooObject)

Notice that java.lang.Class does not implement hashCode() method itself, but inherits it from java.lang.Object implicitly. I verified this in jdk 1.8.

Is java.lang.Class safe to use as a key for a java.util.HashMap? Wil myMap.get(Foo.class) always return the values which I put like myMap.put(fooObject.getClass(), fooObject)? Consider the software to have various classloaders and serialization mechanisms. Will it still be the same result? If not... What would be an alternative?

 


Off the top of my head, would there be any reason to just not use the string class names? E.g. instead use:

myMap.put("Foo", fooObject); 

If you are paranoid that maybe there could be more than one Foo class in scope, you could use the full canonical name:

myMap.put(Foo.class.getCanonicalName(), fooObject); 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: