I wrote a method that gets a random value from a Map
. I first got all the values in the map and use a Random
object to get a random one. Here is the method:
public static <K, V> V getRandomValInMap (Map<K, V> map) {
Collection<V> values = map.values ();
V[] array = (V[])values.toArray ();
return array[random.nextInt (array.length)];
}
In the expression
(V[])values.toArray ()
Android Studio said that it is an "unchecked cast from Object[]
to V[]
". So I guess this is kind of "risky". I tried using another overload of toArray
:
V[] array = new V[values.size()];
array = values.toArray (array);
And I guess this is not how you would use the overload because there's a compiler error saying that I cannot initialize V
.
So I think maybe I should use the first method. But how do I "check" a cast to cancel the warning?
Or, you can tell me how to use the toArray(T[] array)
overload correctly.