title: Heterogeneous container to store genericly typed objects in Java
body: <p>I am trying to follow Joshua Bloch's typesafe hetereogeneous container pattern from Effective Java to create a container of objects (<code>MyGeneric&lt;T&gt;</code>) with <code>Class&lt;T&gt;</code> as a key.</p>
  
  <pre><code>  public class MyClass {
  
      private Map&lt;Class&lt;?&gt;, MyGeneric&lt;?&gt;&gt; myContainer =
        new HashMap&lt;Class&lt;?&gt;, MyGeneric&lt;?&gt;&gt;();
  
      public &lt;T&gt; void addToContainer(Class&lt;T&gt; class, MyGeneric&lt;T&gt; thing) {
        myContainer.put(class, thing);
      }
  
      public &lt;T&gt; MyGeneric&lt;T&gt; getFromContainer(Class&lt;T&gt; class) {
        return (MyGeneric&lt;T&gt;)(myContainer.get(klass));
      }
    }
  </code></pre>
  
  <p>The problem is in getFromContainer I have to perform a unchecked cast. In Josh Bloch's container, he performs a safe cast - but in my case I can't see a way how this is possible.</p>
  
  <p>Does any one have any ideas?</p>
  
  <p>Cheers,
  Nick.</p>