1// generic methods
2
3public <T> List<T> fromArrayToList(T[] a) {
4 return Arrays.stream(a).collect(Collectors.toList());
5 }
6
7public static <T, G> List<G> fromArrayToList(T[] a, Function<T, G> mapperFunction) {
8 return Arrays.stream(a)
9 .map(mapperFunction)
10 .collect(Collectors.toList());
11 }
12
13// bounded generics
14
15public <T extends Number> List<T> fromArrayToList(T[] a) {
16 ...
17 }
18
19//multiple bounds
20
21<T extends Number & Comparable>
22
23// upper bound wildcards
24
25public static void paintAllBuildings(List<? extends Building> buildings) {
26 ...
27 }
28
29// lower bound wildcard
30
31<? super T>
1Java 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:
2
3E – Element (used extensively by the Java Collections Framework, for example ArrayList, Set etc.)
4K – Key (Used in Map)
5N – Number
6T – Type
7V – Value (Used in Map)
8S,U,V etc. – 2nd, 3rd, 4th types