Creating Generic Type Random Values ​​in Java

I have the following:

public class RandomList { private List<Integer> list; public List<Integer> getList() { return list; } public RandomList (int n) { list = new ArrayList<Integer>(); Random rand = new Random(); rand.setSeed(System.currentTimeMillis()); for (int i=0; i < n; i++) { Integer r = rand.nextInt(); list.add(r); } } } 

which gives me a list filled with random Integer values. I would like to generalize this to get a list of random values ​​of characters or, possibly, lists of random values ​​of other types.

So what I want is a version of a generic type, class RandomList<T> . I can replace everywhere "Integer" with "T", but stuck in the line Integer r = rand.nextInt(); which will read different for different types.

I am going to do the following:

  • pass a generic type class to RandomList
  • using instanceof check the passed class for the desired types (Integer, Character ...) and, depending on the check, return the correct random value
It makes sense? Is there any other / better way to achieve what I want?
+5
source share
1 answer

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()) 
+6
source

Source: https://habr.com/ru/post/1258992/


All Articles