title: Uniform parameters passing and typesafety with Java generics
body: <p>Since I often have to deal with randomization, I'd like to make a class which conveniently groups all of those functions that I usually need. Among others, I thought of a generic <code>fromPool()</code> function which, given a variable number of objects, returns randomly one of them. Of course I had to combine varargs and generics, which I just discovered could be a big taboo depending on the cases (and I suspect mine is one of those).
  Here's the code:</p>
  
  <pre><code>abstract public class RandomGenerator {
  
      public static int fromRange(int min, int max) {
  
          return (int) (Math.random() * (max + 1 - min)) + min;
      }
  
      public static &lt;T&gt; T fromPool(T ... pool) {
  
          return pool[fromRange(0, pool.length - 1)];
      }
  }
  
  </code></pre>
  
  <p>The problem is that I can of course pass to <code>fromPool()</code> objects of different kinds, making the return type extremely variable. So, for example, I can do something like this:</p>
  
  <pre><code>int n = (int) RandomGenerator.fromPool("String", 6);
  
  </code></pre>
  
  <p>Which will work until <code>fromPool()</code> doesn't return "String", then causing this exception to be thrown.</p>
  
  <blockquote>
    <p>Exception in thread "main" java.lang.ClassCastException: class
    java.lang.String cannot be cast to class java.lang.Integer
    (java.lang.String and java.lang.Integer are in module java.base of
    loader 'bootstrap')   at Test.main(Test.java:109)</p>
  </blockquote>
  
  <p>Here's what I was wondering:</p>
  
  <p>1) Is this what the "Type safety: Potential heap pollution via varargs parameter pool" warning which appears when combining generics and varargs refers to? Is there something more to it?</p>
  
  <p>2) Isn't there a way to limit the generics effect so that you couldn't pass objects that aren't in any way compatible to each other to the same function call? Basically some kind of automatic, transversal overloading (I feel like I'm asking for the moon)?</p>
  
  <p>3) I had actually previously wrote a much less generic version of <code>fromPool()</code> which only dealt with Number objects.</p>
  
  <pre><code>public static &lt;N extends Number&gt; N fromPool(N ... pool) {
  
      return pool[fromRange(0, pool.length - 1)];
  }
  </code></pre>
  
  <p>Contrary to what I initially believed, it ends this version is unsafe as well because while casting between primitive types doesn't create any problems, casting between the various wrapper classes is not possible, so causing once again ClassCastExceptions. Isn't there a way to tweak this version in order to make at least this one safe?</p>
  
  <p>Thank you very much for your insight :)</p>