Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type safe heterogeneous container pattern to store lists of items

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

like image 853
Javier Ferrero Avatar asked Jun 30 '11 22:06

Javier Ferrero


People also ask

What is heterogeneous container?

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.

What is heterogeneous value in Java?

"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.


1 Answers

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

like image 70
irreputable Avatar answered Sep 20 '22 19:09

irreputable