title: Generic method triggers type safety error - why?
body: <p>Whilst playing around with solutions for <a href="https://stackoverflow.com/questions/23760662/instantiating-object-without-knowing-the-concrete-type">this question</a>, I came up with the following code, which has some compiler warnings. One warning is:</p>
  
  <blockquote>
    <p><code>Type safety: The expression of type Test.EntityCollection needs unchecked conversion to conform to Test.EntityCollection&lt;Test.Entity&gt;</code></p>
  </blockquote>
  
  <p>I don't entirely understand why this warning appears. By passing in a <code>Class&lt;M&gt;</code> type and declaring the method returns <code>EntityCollection&lt;M&gt;</code>, why am I not doing enough to convince the (Java 7) compiler that the correct type is being returned?</p>
  
  <pre><code>static class Entity {
  }
  
  static class EntityCollection&lt;E extends Entity&gt; {
  
      private EntityCollection(HashMap&lt;?, E&gt; map) {
      }
  
      public static &lt;T extends HashMap&lt;?, M&gt;, M extends Entity&gt; EntityCollection&lt;M&gt; getInstance(
              Class&lt;T&gt; mapType, Class&lt;M&gt; entityType)
              throws ReflectiveOperationException {
  
          T map = mapType.getConstructor().newInstance();
          return new EntityCollection&lt;M&gt;(map);
      }
  }
  
  public static void main(String[] args) throws Exception {
      // both compiler warnings are on the line below:
      EntityCollection&lt;Entity&gt; collection = EntityCollection.getInstance(
              LinkedHashMap.class, Entity.class);
  }
  </code></pre>
  
  <p>Bonus points if anyone can improve the code to avoid warnings entirely. I've been staring at it for a while and haven't dreamt up any ways to lessen the warnings.</p>