title: Type safe heterogeneous container pattern to store lists of items
body: <p>I'm trying to implement a type-safe heterogeneous container to store lists of heterogeneous objects.</p>
  
  <p>I have seen several exameples of type-safe heterogeneous container pattern (<a href="https://stackoverflow.com/questions/416540/java-map-with-values-limited-by-keys-type-parameter">link</a>) but all of them store a single object of a type. </p>
  
  <p>I have tryed to implement it as follows:</p>
  
  <pre><code>public class EntityOrganizer {  
  
      private Map&lt;Class&lt;?&gt;, List&lt;Object&gt;&gt; entityMap = new HashMap&lt;Class&lt;?&gt;, List&lt;Object&gt;&gt;();
  
      public &lt;T&gt; List&lt;T&gt; getEntities(Class&lt;T&gt; clazz) {
          return entityMap.containsKey(clazz) ? entityMap.get(clazz) : Collections.EMPTY_LIST;
      }
  
      private &lt;T&gt; void addEntity(Class&lt;T&gt; clazz, T entity) {
          List&lt;T&gt; entityList = (List&lt;T&gt;) entityMap.get(clazz);
          if(entityList == null) {
              entityList = new ArrayList&lt;T&gt;();
              entityMap.put(clazz, (List&lt;Object&gt;) entityList);
          }
          entityList.add(entity);
      }   
  }
  </code></pre>
  
  <p>But the problem is this code is full of unchecked casts. Can someone help with a better way of implementing this?</p>
  
  <p>Many thanks</p>