简体   繁体   中英

Random selection from a heap of classes in Java

I have a best technique issue in Java. I have a base class implementing some genral methods. An a heap of inherited classes. Now I have to randomly select one of the inherited classes. My approach is the following:

  1. Having a array of the Class object for each inherited class
  2. Randomly generate an index for the array
  3. Create an instance of the class object at the random index from 2. with newInstance()

Code exmaple for step 1:

Class[] possibleClasses = {Class1.class, Class2.class}

Is this a sufficient approach? For example the Eclipse Indigo syntax correction says for the code example above "Class is a raw type. References to generic type Class should be parameterized". So the definition without generic type may has side effects or so?

Stefan

Your approach is fine - indeed it's probably the simplest and most effective approach.

If you want to avoid the compiler warning you can add a generic type argument as follows:

Class<?>[] possibleClasses = new Class[]{Class1.class, Class2.class}

However this just gives you a different warning (unchecked conversion) so you might as well just suppress the original warning directly.

A slightly more complex alternative approach would be to use reflection to walk the class hierarchy and automatically add all subclasses of your base class to an ArrayList of classes. The advantage is that you wouldn't need to explicitly list out all the subclasses individually and it would automatically pick up any new subclasses added.

Since nobody has put this into an answer, I'll say it: use a List . Arrays don't play nice with generic types.

List<Class<? extends MyBaseClass>> possibleClasses = Arrays.asList(Class1.class, Class2.class);

Before Java 7 this will produce a harmless warning:

Unchecked generics array creation for varargs parameter.

This can be safely ignored or suppressed, or you can instead do this:

List<Class<? extends MyBaseClass>> possibleClasses = new ArrayList<...>();
possibleClasses.add(Class1.class);
//...

And then you can generate a random index and use possibleClasses.get(i) .

Class<? extends Collection>[] klazzes =
  (Class<Collection>[]) new Class[]{ List.class, Set.class };

Ok, people seem to have a really hard time coming up with the code. You should do something like this:

Class<?>[] cls = {Class1.class, Class2.class};
Random r = new Random();
Class<?> = cls[r.nextInt(cls.length)];

You should reuse the instance of Random from call to call to ensure distribution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM