I have always used generics and always seen the angle brackets used like this: Class<Type>
(e.g. List<String>
).
Today I encountered a generics specification before the call of a static method like: Class.<TypeA, TypeB>staticCall()
. The real example is: ImmutableMap.<String, String>builder()
.
I've never seen this usage and I can't find this specific usage in the documentation. Can someone explain what is going on, please?
Those are called Generic Methods.
Before Java 7 you had to specify the type of the Generic reference:
Now the compiler infers the type from the context.
It's signifying multiple types. List only takes one generic type which is why you see
From the java docs for Map
At the top you'll see: Interface Map
so it takes two generic types. In the example of your Immutable map, it's saying that the K(ey) is a String and V(alue) is also a String.
In the link you provided, it mentions that this is possible under section,
we can define generics on class level also .
ImmutableMap.Builder means Builder is inner static class here .
and Builder methods will have K and V as arguments means
means instead providing put(String , String) it provides methos like put(K,V) so that any type can be added using put and if you get you need use the same type.
for example if your are calling Builder.Put by passing string , String then in get we can directly assign to String
String val = Bullder.get(K);
it means all methods of ImmutableMap.Builder will work for any class type.
that is the power of generics meaning no need to overlaod methods for different type. just define like below: