The first method (bottom)
In Java, you cannot check the generic type, at least not without reflection. You have money with a generic type, so you would do something like this:
public class RandomList<T> { private List<T> list; private Class<T> clazz; public List<T> getList() { return list; } public RandomList (Class<T> clazz, int n) { this.clazz = clazz; list = new ArrayList<T>(); Random rand = new Random(); rand.setSeed(System.currentTimeMillis()); if (clazz.isAssignableFrom(Integer.class)) { for (int i = 0; i < n; i++) { Integer r = rand.nextInt(); list.add(r); } } else { throw new IllegalArgumentException("Unsupported class: " + clazz.getName()); } } }
Second method (excellent)
Alternatively, you can generalize this one more time and add Function to get randomized results. Please note that this requires Java 8. If you are not on Java 8, you can simply define the interface and build anonymously.
public class RandomList<T> { private List<T> list; public List<T> getList() { return list; } public RandomList (Function<Random, T> creator, int n) { list = new ArrayList<T>(); Random rand = new Random(); rand.setSeed(System.currentTimeMillis()); for (int i = 0; i < n; i++) { list.add(creator.apply(rand)); } } }
Create a new instance using:
RandomList<Integer> list = new RandomList<>(rand -> rand.nextInt(), 10);
The third method (cleaner)
Edit: this happened to me later, but you seem to be using Java 8, so you can just use threads:
List<Integer> list = Stream.generate(() -> rand.nextInt()).limit(10).collect(Collectors.toList())
source share