0

For my current project I want a class to create random values (integers for example). I am a big fan of giving my methods a sentence-like signature and my int-generate should be called like this:

Generate.randomIntBetween(0).and(10);

A pretty simple implementation for that would be something like this:

public static UpperBound generateIntBetween(int lowerBound) {
    return upperBound -> {
        return (int) (Math.random()*(upperBound - lowerBound) + lowerBound); 
    };
}

However this solution might be dangerous when the range is really big:

Generate.randomIntBetween(Integer.MIN_VALUE).and(Integer.MAX_VALUE);

Is there a simple and safe implementation that will not break for big ranges? Could I simple use ThreadLocalRandom.nextInt(int, int)?


"Generating random integers in a specific range" has no answer for handling the int-overflow
danielspaniol
  • 1,898
  • 14
  • 34
  • `ThreadLocalRandom.nextInt` will probably do the job, since the JDK is good about documenting invalid parameters. – 4castle Aug 31 '16 at 07:31
  • You could eliminate all your concerns about overflow by using `BigInteger` - [How to generate a random BigInteger value in Java?](http://stackoverflow.com/questions/2290057/how-to-generate-a-random-biginteger-value-in-java) – OldCurmudgeon Aug 31 '16 at 07:33
  • No, `ThreadLocalRandom` has an exclusive upperbound (`and` sounding inclusive). As `-` can overflow, use `Random.nextInt` and trim the overflow. – Joop Eggen Aug 31 '16 at 07:48
  • `and` was actually meant to be exclusive... but if it sounds inclusive I have to overthink that name. What exactly do you mean by "use Random.nextInt and trim the overflow"? – danielspaniol Aug 31 '16 at 08:03

0 Answers0