This works:
Random generator = new Random();
Object[] values = myHashMap.values().toArray();
Object randomValue = values[generator.nextInt(values.length)];
If you want the random value to be a type other than an Object
simply add a cast to the last line. So if myHashMap
was declared as:
Map<Integer,String> myHashMap = new HashMap<Integer,String>();
The last line can be:
String randomValue = (String) values[generator.nextInt(value.length)];
The below doesn't work, Set.toArray()
always returns an array of Object
s, which can't be coerced into an array of Map.Entry
.
Random generator = new Random();
Map.Entry[] entries = myHashMap.entrySet().toArray();
randomValue = entries[generator.nextInt(entries.length)].getValue();
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…