samedi 29 octobre 2016

Create random values of generic typein 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 also get a list of random Character values or perhaps lists of other types' random values.

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

I am thinking of doing the following:

  1. pass in the class of the generic type to RandomList
  2. using instanceof check the passed in class against the desired types (Integer, Character...) and depending on the check return the proper random value

Does this make sense? Is there another/better way to achieve what I want?




Aucun commentaire:

Enregistrer un commentaire