Reputation: 12484
I'm studying code from Horstmann's java book:
Integer key = new Random().nextInt(elements.length) + 1;
What puzzles me is the +1 part , is there any reason for this, or just for more "randomness"? Thanks alot!
Upvotes: 1
Views: 78
Reputation: 158599
is there any reason for this, or just for more "randomness"?
No this does not add "randomness", 1
is clearly not random, this is to shift the range from [0,elements.length-1]
to [1,elements.length]
.
Upvotes: 2
Reputation: 27812
I think the +1
is to shift the domain of random integers, from
[0,elements.length-1]
to
[1, elements.length]
Horstmann simply wants a random integer from 1 to elements.length for his key.
Upvotes: 3
Reputation: 887857
nextInt()
returns a number more than or equal to zero and less than its parameter.
+ 1
shifts that range.
Upvotes: 4