commons-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Simon Spero <sesunc...@gmail.com>
Subject Re: [RNG] Generating for [e]nums
Date Fri, 04 Aug 2017 19:29:42 GMT
On Aug 4, 2017 2:11 PM, "Gary Gregory" <garydgregory@gmail.com> wrote:

For example, I have a enum like:

public enum CardinalDirection (NORTH,SOUTH,EAST,WEST)

public CardinalDirection nextRandomDirection() {
   return rng.next(CardinalDirection.class);
}


This approach may be a bit slow if the random values are near an inner
loop.

In order to select a random enum value, you need to get hold of an array
containing all the possible values (equivalent to what gets returned by the
generated  "public static CardinalDirection[] values()".

This requires calling Class::getEnumConstants, which does a little
reflection, caches the result, then returns a clone of the resultant array.

It may be better to construct a random enum value generator object that
holds a copy of the values array, plus an RNG with the desired
characteristics.

A more general method would take an array of values, or a Supplier<T[]>
function (e.g. CardinalDirection::values).

You could use a cache in the RNG, keyed by the class, but that's still
going to be a bit expensive in the middle of a tight loop.

Simon

Simon

Mime
  • Unnamed multipart/alternative (inline, None, 0 bytes)
View raw message