Is there a specific reason why you are requesting a more effective solution? If this function is not in a very dense inner loop somewhere (for example, in a ray tracer), you can try to optimize your code prematurely.
If you want to avoid the array, and if you don't like the "bloat" if-statement, you can use the triple select operator to choose between two:
int a = 35; int b = 70; int c = random.nextBoolean() ? a : b;
where random is an instance of java.util.Random . You can save this instance as a final static field in your class to reuse it.
If you do not require true randomness, but just want to switch between two numbers each time you call this block of code, you can leave by simply saving boolean and switching it:
... int c = toggle ? a : b; toggle = !toggle;
Since I cannot comment on other answers, I would like to point out a problem with some other answers that involve creating a random integer in a larger range and making a decision based on whether the result is odd or even if it is less than or greater than the average. This is actually the same as generating a random integer from 0 to 1, except for an overly complex one. The nextInt(n) method uses the modulo operator for a randomly generated integer between -2 ^ 31 and (2 ^ 31) -1, which is essentially what you will do in the end, just with n = 2 .
If you use standard library methods such as Collections.shuffle() , you will again be overly complex because the standard library uses a random number generator in the standard library.
Note that all sentences are (so far) less efficient than my simple nextBoolean() , because they require unnecessary method calls and arithmetic.
source share