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?
CodePudding user response:
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.
CodePudding user response:
Having method such this:
public <T> List<T> fromArrayToList(T[] a) {
return Arrays.stream(a).collect(Collectors.toList());
}
Makes only this method generic and T is valid in method domain.
But this one is class level generic that makes T available in any method of class.
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;
}
List<T> fromArrayToList(T[] a) {
return Arrays.stream(a).collect(Collectors.toList());
}
}
I have added your method in class and you can better figure out difference. As you see in method level generic is declared in method signature but in class level generic is declared in class signature.
So in first case you have Generic Method and in second case you have Generic Class
Obviously you use declare generic method when you need make only a method generic, but generic class is used in cases that generic type need to be used in different methods of class.