java: method nextLong in class java.util.Random cannot be applied to given types;

94 Views Asked by At

Here's the simple method that gave me the error:

protected static long random(long a, long b) {
    //Random random = new Random();
    return a + new Random().nextLong(b - a);
}

And here are the errors from the terminal:

java: method nextLong in class java.util.Random cannot be applied to given types;

  required: no arguments

  found:    long

  reason: actual and formal argument lists differ in length
1

There are 1 best solutions below

2
Rogue On

Using ThreadLocalRandom, there's no need for your helper method:

long origin = 0;
long bound = 1000;
//A random long in the range [0, 1000)
long rand = ThreadLocalRandom.current().nextLong(origin, bound);

This is available in Java 7 and later. Earlier on, Random did not have some of the helper methods provided through RandomGenerator (in Java 17), so you only have the Random#nextLong() method (with no arguments). This number had to be manually modulo'd, which can lead to distribution issues down the line. It's much better to use ThreadLocalRandom here in this case, as it will be uniformly distributed.