Skip to content
Advertisement

How to declare a generic method in Java?

I am learning Java generics and am confused by the method signature. It seems as if people are using it differently in every example I come across.

For example, on the site Baeldung, this is the example they give:

JavaScript

And then they go on to say this:

The <T> in the method signature implies that the method will be dealing with generic type T. This is needed even if the method is returning void.

But the <T> is not required in this example. Why?

JavaScript

What does a generic method signature actually look like? I am seeing many different examples that all look different. When does a method require <T> before the return type and when does it not?

Advertisement

Answer

In that example, the class is made generic, so T is specified when you instantiate it. The method is different because it need not be in a generic class.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement