0

Hi I will be generating a Random number

Random randomno = new Random();
int random = randomno.nextInt(10000);

I want use this random number value in different class. If I create the Object of this class, every time this values changes. But for one execution I want to maintain one value throughout the application.

3
  • 2
    I suggest you store it in a field of the object. Commented Aug 16, 2016 at 7:17
  • Even better a final field Commented Aug 16, 2016 at 7:18
  • Paolo has a point, but also you could think of adding this into a method and not a class.... it would be more functional... Commented Aug 16, 2016 at 7:20

2 Answers 2

2

If you want to have a re-usable method to generate a random number, you could create a special class that does that for you:

import java.util.Random;

public class RandomNumberGenerator {

    private static final Random RANDOM = new Random();


    private RandomNumberGenerator() {

    }

    //Usage: RandomNumberGenerator.getRandomNumber(10000);
    public static int getRandomNumber(int max) {
        return RANDOM.nextInt(max);
    }
}

This can in turn be used in another class and results can be saved to an arraylist or whatever you like. Example demo:

public class Main {
    public static void main(String[] args) {
        final List<Integer> randomNumbers = new ArrayList<>();

        for (int i = 0; i < 10; i++) {
            randomNumbers.add(RandomNumberGenerator.getRandomNumber(10000));
        }
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Random number generated from RandomNumberGenerator can be used anywhere and these random will get stored in Main class ?
That depends on where you save them: if you wanted to you could declare a static List<Integer> in the RandomNumberGenerator class and store them in there, so the random numbers are maintained throughout the entire application.
0

Possible way:

1) Add your code in application class, and there make one field as static, any anywhere you want this field you can use it. (recommended)

2) Store data in shared pred or db.

3) make a singleton pattern which is answer given by nbokmans user.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.