How to generate random integers within a specific range in Java?
How to generate a random int
value in a specific range?
The following methods have bugs related to integer overflow:
randomNum = minimum + (int)(Math.random() * maximum);
// Bug: `randomNum` can be bigger than `maximum`.
Random rn = new Random();
int n = maximum - minimum + 1;
int i = rn.nextInt() % n;
randomNum = minimum + i;
// Bug: `randomNum` can be smaller than `minimum`.
There are several differences between
HashMap
andHashtable
in Java:Hashtable
is synchronized, whereasHashMap
is not. This makesHashMap
better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones.Hashtable
does not allownull
keys or values.HashMap
allows onenull
key and any number ofnull
values.LinkedHashMap
, so in the event that you’d want predictable iteration order (which is insertion order by default), you could easily swap out theHashMap
for aLinkedHashMap
. This wouldn’t be as easy if you were usingHashtable
.Since synchronization is not an issue for you, I’d recommend
HashMap
. If synchronization becomes an issue, you may also look atConcurrentHashMap
.