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
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…