I am trying to populate an array (probCount) using a SecureRandom object (index) to determine probabilities. I have a for loop to run this about 100 million times:
probCount[index.nextInt(probCount.length)]++;
When I print the array, all my elements are populated correctly. How does this line does not throw an out of bounds exception?
I had it like:
probCount.length - 1
This, however, never populated my last element. I am a bit confused.
From the Random.nextInt(int)
documentation:
Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)
...
Parameters:
bound
- the upper bound (exclusive). Must be positive.
Note the "exclusive" part. So for example, if you call index.nextInt(5)
it will return 0, 1, 2, 3 or 4... which are precisely the valid indexes for an array of length 5.
See more on this question at Stackoverflow