How to "check" listing?

I wrote a method that gets a random value from Map. First, I got all the values ​​on the map and used the object Randomto 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).

+4
5

aproach :

public static <K, V> V getRandomValInMap (Map<K, V> map) {
    Collection<V> values = map.values ();

    Iterator<V> it = values.iterator();
    int choosen = new Random().nextInt (values.size());
    for (int i=0; i<values.size();i++) {
        V value = it.next();
        if (i==choosen) return value;
    }
    throw new AssertionError("Choosen value out of bounds");
}
+1

, Java, . : V[] array = new V[values.size()];

. :

, Java?

+2

, instanceof, , , - - . , , .

new V - . Java, , .

, , .

0

Java erasure, generics Object.

You can suppress the warning:

public static <K, V> V getRandomValInMap (Map<K, V> map) {
    Collection<V> values = map.values ();
    @SuppressWarnings("unchecked") V[] array = (V[])values.toArray ();
    return array[1];
}
0
source

Quote: Bruce Ekel in thinking in Java using Array.newInstance is the recommended approach for creating arrays in generics.

public class ArrayMaker<T> { 
 private Class<T> kind; 
 public ArrayMaker(Class<T> kind) { this.kind = kind; } 
 @SuppressWarnings("unchecked") 
 T[] create(int size) { 
  return (T[])Array.newInstance(kind, size); 
 }
}

You can use this approach and populate your array with the keys and values ​​of your card.

0
source

Source: https://habr.com/ru/post/1611896/


All Articles