Keywords: Java | random | long | range | ThreadLocalRandom
Abstract: This article explores methods for generating random long numbers within a specified range in Java, covering the use of ThreadLocalRandom, custom implementations, and alternative approaches, with analysis of their pros, cons, and applicable scenarios. It is based on technical Q&A data, extracting core knowledge to help developers choose appropriate methods.
Introduction
In Java programming, the Random class provides the nextInt(int bound) method to generate random integers within a specified range, but for long types, there is no direct method to set a range. This may lead developers to seek alternative solutions.
Using ThreadLocalRandom (Java 7 and Above)
Starting from Java 7, the ThreadLocalRandom class offers convenient methods for generating random numbers. For long numbers, you can use ThreadLocalRandom.current().nextLong(long bound) to generate a random long from 0 (inclusive) to bound (exclusive). Additionally, nextLong(long origin, long bound) allows specifying both lower and upper bounds.
// Example usage
long randomValue = ThreadLocalRandom.current().nextLong(100); // generates 0 to 99
long rangedValue = ThreadLocalRandom.current().nextLong(10, 100); // generates 10 to 99This class is thread-safe, suitable for multi-threaded environments, and performs efficiently.
Custom Implementation for Compatibility
For environments like Java 6 or older Android versions, a custom method can be implemented based on the algorithm of Random.nextInt. The key is to ensure uniform distribution and avoid bias.
public static long nextLongInRange(Random rng, long bound) {
if (bound <= 0) {
throw new IllegalArgumentException("bound must be positive");
}
long bits, val;
do {
bits = rng.nextLong() & Long.MAX_VALUE; // clear sign bit for non-negative values
val = bits % bound;
} while (bits - val + (bound - 1) < 0);
return val;
}This method mimics the behavior of nextInt using rejection sampling to maintain uniformity. Special characters in the code, such as < and &, are HTML-escaped to prevent parsing errors.
Alternative Approaches and Considerations
Another approach involves using nextDouble() multiplied by the desired range. For example:
long number = (long) (new Random().nextDouble() * range);However, this method may suffer from precision loss, leading to uneven distribution, especially for large values, and is not recommended for applications requiring exact distribution.
Conclusion
For modern Java development, ThreadLocalRandom is recommended due to its simplicity and performance. For legacy systems, implement custom methods or use external libraries like Apache Commons Math. When selecting a method, balance simplicity, accuracy, and compatibility.