title: Generic List initialization in java
body: <p>I have a problem with the initialization of a List . The Class of the Items isn't known at compile time - they could be int, float, string or custom classes.</p>
  
  <p>So I tried this:</p>
  
  <pre><code>public class Sensordevice {
      private List&lt;?&gt; valueList;
  
      public void setValueList(List&lt;?&gt; valueList) {
          this.valueList = valueList;
      }   
  
      public void addValue(Object value) {
          if(valueList == null){
              valueList = getList(value.getClass());
          }
          valueList.add(value);
      }
  
      private &lt;T&gt; List&lt;T&gt; getList(Class&lt;T&gt; requiredType) {
          return new ArrayList&lt;T&gt;();
      }
  }
  </code></pre>
  
  <p>But I get this Error at valueList.add(value) in the addValue Methode:</p>
  
  <blockquote>
    <p>The method add(capture#4-of ?) in the type List is not applicable for the arguments (Object)</p>
  </blockquote>
  
  <hr>
  
  <p>Update</p>
  
  <p>Thanks a lot for your replies. This solution works for my.</p>
  
  <pre><code>public class Sensordevice&lt;T&gt; {
      private List&lt;T&gt; valueList;
  
      public void setValueList(List&lt;T&gt; valueList) {
          this.valueList = valueList;
      }   
  
      public void addValue(T value) {
          if(valueList == null){
              valueList = new ArrayList&lt;T&gt;();
          }
          valueList.add(value);
      }
  }
  </code></pre>