RFR 8023155: Ensure functional consistency across Random, ThreadLocalRandom, SplittableRandom

Guy Steele guy.steele at oracle.com
Mon Aug 19 20:12:36 UTC 2013


On Aug 19, 2013, at 3:17 PM, Mike Duigou <mike.duigou at oracle.com> wrote:

> - documentation of "bound" should mention that it is exclusive rather than relying on the return documentation.

Agreed.

> - I find disallowing the zero bounds and empty ranges slightly annoying. It requires me to externally special case for situations such as:
> 
> Random ran = new Random();
> String[] users = {"Fred"}; 
> 
> someUser = users[mine.nextInt(users.length - 1)];
> 
> This is a frequently used idiom. Yes, forcing the random number generator to return zero is silly but for symmetry it is convenient. An empty range isn't an obvious error (though the "String[] users = {};" case is obviously an error).

But I am puzzled here.  Is it really a frequently used idiom to want to set "someUser" to any element of the array "users" EXCEPT the last one?  Because that is what is asked for by

   someUser = users[mine.nextInt(users.length - 1)];

If you want a free choice among ALL elements in the (non-empty) array, then

   someUser = users[mine.nextInt(users.length)];

is what you want; and if the array is empty, then you'll get an exception from the nextInt method rather than the array indexing step, but that amounts to the same thing: an inability to pick an element from an empty array.

--Guy




More information about the core-libs-dev mailing list