Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare a generic method in Java?

Tags:

java

generics

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?

like image 694
mastercooler6 Avatar asked Dec 17 '25 15:12

mastercooler6


1 Answers

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.

like image 100
ndc85430 Avatar answered Dec 20 '25 04:12

ndc85430



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!