Java : Generic Methods

I came across Generic types when I was first learning java in 2013. I put some effort to understand them and started using them. Most the of the regular programming involves using a generic type than defining one. Like every one uses Collections, its pretty rare we have to define a costume collection type. Following is a generic pair class which allows you to hold any two objects

What I was not aware until recently is that java also supports Generic methods. I had a requirement to write a custom collector for a stream. So I was looking the method signature of Collectors.toList().

public static <T> Collector<T, ?, List<T>> toList()

T defines a type parameter scoped to the method. We can define them for both static and non-static methods.

There are plenty of places where generic methods are used, If you have ever used gson library, you could have seen that we don’t need to type cast the result of fromJson method. Its because `fromJson` is generic method. We can call the generic methods like regular methods without specifying the type parameters because compiler can infer them using type inference

public <T> T fromJson(String json, Class<T> classOfT) throws JsonSyntaxException

Java compiler can also infer the type information from the target type. For example in an assignment statement, type information required by RHS expression can be derived from LHS expression. One example might a factory method which provides collection type that can hold number type.

public <T extends Number> Collection<T> getNumberList()
Collection<Long> ls = getNumberList();

Whats your experience with Generics ?

Add a Comment

Your email address will not be published. Required fields are marked *