mercredi 31 août 2016

Java: generate random number in range

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


Aucun commentaire:

Enregistrer un commentaire