I wrote a method that gets a random value from Map
. First, I got all the values on the map and used the object Random
to get random. Here is a way:
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 expression
(V[])values.toArray ()
Android Studio said it was an "uncontrolled screening from Object[]
to V[]
." Therefore, I think this is kind of "risky." I tried using another overload toArray
:
V[] array = new V[values.size()];
array = values.toArray (array);
And I think this is not how you will use overloading, because there is a compiler error saying that I cannot initialize V
.
So, I think, maybe I should use the first method. But how can I “check” the throw to cancel the warning?
, toArray(T[] array)
.