public static <T> T getRandomValue(List<T> listOfPossibleOutcomes, int numPossibilities) {
int r = RandomNumberGenerator.getRandIntBetween(0, numPossibilities);
return listOfPossibleOutcomes.get(r);
}
public static <T> T getRandomValueFromGenericList(List<T> list) {
Collections.shuffle(list);
return list.get(0);
}
Java Generic Type Naming convention helps us understanding code easily and having a naming convention is one of the best practices of Java programming language. So generics also comes with its own naming conventions. Usually, type parameter names are single, uppercase letters to make it easily distinguishable from java variables. The most commonly used type parameter names are:
E – Element (used extensively by the Java Collections Framework, for example ArrayList, Set etc.)
K – Key (Used in Map)
N – Number
T – Type
V – Value (Used in Map)
S,U,V etc. – 2nd, 3rd, 4th types
// generic methods
public <T> List<T> fromArrayToList(T[] a) {
return Arrays.stream(a).collect(Collectors.toList());
}
public static <T, G> List<G> fromArrayToList(T[] a, Function<T, G> mapperFunction) {
return Arrays.stream(a)
.map(mapperFunction)
.collect(Collectors.toList());
}
// bounded generics
public <T extends Number> List<T> fromArrayToList(T[] a) {
...
}
//multiple bounds
<T extends Number & Comparable>
// upper bound wildcards
public static void paintAllBuildings(List<? extends Building> buildings) {
...
}
// lower bound wildcard
<? super T>
public <T> List<T> fromArrayToList(T[] a) {
return Arrays.stream(a).collect(Collectors.toList());
}