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:

public <T> List<T> fromArrayToList(T[] a) {   
    return Arrays.stream(a).collect(Collectors.toList());
}

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?

class MyGenericClass<T>
{  
    T obj;  
    // Why does this function not need <T> before "void"?
    void add(T obj)
    {
           this.obj=obj;
    }  
    T get()
    {
           return obj;
    }  
}  
 
class Main
{  
     public static void main(String args[])
     {  
           MyGenericClass<Integer> m_int=new MyGenericClass<Integer>();  
           m_int.add(2);
           MyGenericClass<String>mstr=new MyGenericClass<String>();  
           mstr.add("SoftwaretestingHelp");
 
           System.out.println("Member of MyGenericClass<Integer>:" + m_int.get());
           System.out.println("Member of MyGenericClass<String>:" + mstr.get());
     }
} 

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