I want to create a kind of in-memory database into which I can put objects of any type that extends EntityProxy. I want to index every object according to its type and id number (which every EntityProxy has – something simple like creating a HashMap for each type.
I could implement this manually with something like
public void put(Object o)
{
if (o instanceof Car)
carIndex.put(o.getId(), o);
else if (o instanceof Bus)
busIndex.put(o.getId(), o);
...
}
But of course I don’t want to. I want something more like
public void <T extends EntityProxy> put(T o)
{
indexMap.get(o.class).put(o.getId(), o);
}
I just don’t quit have the generics vocabulary to do this. I don’t know what the question mark means in template definitions, really – will something like
HashMap<Class<?>, HashMap<Long, EntityProxy>> indexMap
work?
That map is OK; if you really need to add a tiny bit of constraint, just try:
This would make sure the key class can only be an EntityProxy.class or subclass.
You can think of the question mark as some “anything”, but anonymous. So
<?>means really anything — anyObject,<? extends EntityProxy>means anything that fulfils this condition (passes the “instanceof EntityProxy” test).The type safety here is less than desired, as you can still put anything as key and anything in that map. I mean, you can legally put this in the map:
(assuming
EntityProxy1andEntityProxy2are both subclasses ofEntityProxy) since there’s no correlation between the key and the value. To enforce that, theput()method of the map would need to be declared like this:Tis pretty much like?but the main difference is that it provides you with a name that you can refer to it in that context.So, if I said that
?stands for “anything”, I would sayTstands for “something”, as you can refer to that something once you declare it.But you would need a custom data structure for this, as
java.util.Mapdoes not provide this kind of constraint. If you’re using it as shown in your code sample, I don’t think you really need these enforcements.