I'm trying to implement a type-safe heterogeneous container to store lists of heterogeneous objects.
I have seen several exameples of type-safe heterogeneous container pattern (link) but all of them store a single object of a type.
I have tryed to implement it as follows:
public class EntityOrganizer {
private Map<Class<?>, List<Object>> entityMap = new HashMap<Class<?>, List<Object>>();
public <T> List<T> getEntities(Class<T> clazz) {
return entityMap.containsKey(clazz) ? entityMap.get(clazz) : Collections.EMPTY_LIST;
}
private <T> void addEntity(Class<T> clazz, T entity) {
List<T> entityList = (List<T>) entityMap.get(clazz);
if(entityList == null) {
entityList = new ArrayList<T>();
entityMap.put(clazz, (List<Object>) entityList);
}
entityList.add(entity);
}
}
But the problem is this code is full of unchecked casts. Can someone help with a better way of implementing this?
Many thanks
Heterogenous containers, as opposed to regular homogenous containers, are containers containing different types; that is, in homogenous containers, such as std::vector , std::list , std::set , and so on, every element is of the same type. A heterogeneous container is a container where elements may have different types.
"homo-" means same, "hetero-" means different. In any case if a single Java array can only store one type, say, only numbers, or only strings then it is homogeneous. If multiple types then heterogeneous. In the above case, since collection is of Object type and can hold any type.
The question is, what is "unchecked cast"?
Sometimes casts are provably safe, unfortunately the proof is beyond javac's capability, which does only limited static analysis enumerated in the spec. But the programmer is smarter than javac.
In this case, I argue that these are "checked casts", and it's very appropriate to suppress the warning.
See 2 other related examples:
Heterogeneous container to store genericly typed objects in Java
Typesafe forName class loading
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With