title: Java Generics limitations or wrong usage?
body: <p>I have a class representing a pair of two values of the same type (type which can be any of  a specific set of types ): </p>
  
  <pre><code>  public class Pair&lt;E extends AClass&gt;{
        private E var1;
        private E var2; 
    }
  </code></pre>
  
  <p>This class is used by a framework, so it needs a no-argument constructor in which I have to instantiate the 2 variables (var1, var2): </p>
  
  <pre><code>  public class Pair&lt;E extends AClass&gt;{
        private E var1;
        private E var2; 
  
        public Pair(){
             var1 = invoke constructor of type E; 
             var2 = invoke constructor of type E 
        }
    }
  </code></pre>
  
  <p>There are obviously a number of problems here: </p>
  
  <ol>
  <li><p>In order to instantiate the variables I should somehow know its exact type and invoke that specific type's constructor; in the best case this means to have a pretty large if else  statement in the constructor, something like: </p>
  
  <pre><code> public Pair(){
         if(var1 instanceof SpecificType1){
            var1 = new SpecificType1(); 
            var2 = new SpecificType2();
         }
    }
  </code></pre></li>
  <li><p>Even if I do as above, I will have some problems because var1 is declared of type E and I will get a type mismatch error when trying to instantiate SpecficType1 and to assign the resulted object to var1/var2. In order to make it work, I have to cast to E : </p>
  
  <pre><code>   var1 = (E)new SpecificType1();
  </code></pre></li>
  </ol>
  
  <p>But this destroys the compile time type checking as I'm trying to cast a specific type to a generic type.</p>
  
  <p>Is this a limitation of the Generics in java or is this scenario a bad one for using Generics ?</p>