Java Algorithms How to - Generate a random number between multiple ranges


We would like to know how to generate a random number between multiple ranges.


import java.util.ArrayList;
import java.util.List;
import java.util.Random;
// www. java2  s  .c o  m
public class Main {
  public static void main(String[] args) {
    RandomInRanges rir = new RandomInRanges(1, 10);
    rir.addRange(50, 60);

class RandomInRanges {
  private final List<Integer> range = new ArrayList<>();

  RandomInRanges(int min, int max) {
    this.addRange(min, max);

  final void addRange(int min, int max) {
    for (int i = min; i <= max; i++) {

  int getRandom() {
    return this.range.get(new Random().nextInt(this.range.size()));


The code above generates the following result.