J2SE 1.4 includes a java.lang.Math class that provides a mechanism to get a random double value between 0.0 and 1.0, but you need to create random boolean values, or random int variables between zero and a specified
number.
Generate random variables with Commons Lang RandomUtils, which provides a mechanism to
generate random int, long, float, double, and boolean variables. The following code
generates a random integer between zero and the value specified in the
parameter to nextInt( ) :
import org.apache.commons.lang.math.RandomUtils; // Create a random integer between 0 and 30 int maxVal = 30; int randomInt = RandomUtils.nextInt( maxVal );
Or, if your application needs a random boolean variable, create one with a call to the static method
nextBoolean( ):
import org.apache.commons.lang.math.RandomUtils; boolean randomBool = RandomUtils.nextBoolean( );
A frequent argument for not using a utility like RandomUtils is that the same task can be achieved with only one line
of code. For example, if you need to retrieve a random integer between 0
and 32, you could write the following code:
int randomInt = (int) Math.floor( (Math.random( ) * (double) maxVal) );
While this statement may seem straightforward, it does contain a
conceptual complexity not present in RandomUtils.nextInt(maxVal). RandomUtils.nextInt(maxVal) is a simple
statement: "I need a random integer between 0 and maxVal"; the statement without RandomUtils is translated to a more complex
statement:
I'm going to take a random
doublebetween 0.0 and 1.0, and multiply this number bymaxVal, which has been cast to adouble. This result should be a randomdoublebetween 0.0 andmaxVal, which I will then pass toMath.floor( )and cast to anint.
While the previous statement does achieve the same task as
RandomUtils, it does so by rolling-up
multiple statements into a single line of code: two casts, a call to
floor( ), a call to random() , and a multiplication. You may be able to instantly
recognize this pattern as code that retrieves a random integer, but
someone else may have a completely different approach. When you start to
use some of the smaller utilities from Apache Commons systemwide, an
application will tend toward greater readability; these small reductions
in conceptual complexity quickly add up.
