title: Create random values of generic type in Java
body: <p>I have the following:</p>
  
  <pre><code>public class RandomList {
  
      private List&lt;Integer&gt; list;
  
      public List&lt;Integer&gt; getList() {
          return list;
      }
  
      public RandomList (int n) {
          list = new ArrayList&lt;Integer&gt;();
  
          Random rand = new Random();
          rand.setSeed(System.currentTimeMillis());
  
          for (int i=0; i &lt; n; i++)
          {
              Integer r = rand.nextInt();
              list.add(r);
          }
      }   
  }
  </code></pre>
  
  <p>which gives me a list filled with random Integer values. I would like to generalize this, to also get a list of random Character values or perhaps lists of other types' random values.</p>
  
  <p>So what I want is a generic type version, <code>class RandomList&lt;T&gt;</code>. I can replace everywhere "Integer" by "T", but am stuck at the line <code>Integer r = rand.nextInt();</code> which would read different for different types.</p>
  
  <p>I am thinking of doing the following:</p>
  
  <ol>
  <li>pass in the class of the generic type to RandomList</li>
  <li>using <code>instanceof</code> check the passed in class against the desired types (Integer, Character...) and depending on the check return the proper random value</li>
  </ol>
  
  <p>Does this make sense? Is there another/better way to achieve what I want?</p>