I get confused when I come across a generic method of this sort.
public static <T> T addAndReturn(T element, Collection<T> collection){ collection.add(element); return element; }
I cannot understand why <T>
is required in this method.
Also, what is the difference between generic methods and the methods that use generics syntax?
Generic Class Here, T is the data type parameter. T , N , and E are some of the letters used for data type parameters according to Java conventions. In the above example, you can pass it a specific data type when creating a GenericClass object.
< T > is a conventional letter that stands for "Type", and it refers to the concept of Generics in Java. You can use any letter, but you'll see that 'T' is widely preferred. WHAT DOES GENERIC MEAN? Generic is a way to parameterize a class, method, or interface.
The Java Generics allows us to create a single class, interface, and method that can be used with different types of data (objects). This helps us to reuse our code. Note: Generics does not work with primitive types ( int , float , char , etc).
Generic methods are methods that introduce their own type parameters. This is similar to declaring a generic type, but the type parameter's scope is limited to the method where it is declared. Static and non-static generic methods are allowed, as well as generic class constructors.
> public static <T> T addAndReturn(T > element, Collection<T> collection){ > collection.add(element); > return element; }
The <T>
(in angle brackets) is known as the generic type parameter, whereas the T
directly preceeding the method name is the return type. You might have a generic method that returns some other type than the generic type. Perhaps you want a method that adds an element to a collection (so an object of type T
), and rather than returning the added object (which would also be of type T
), you want it to return the index of that item in the collection, which would always be an int.
Example method signature where the return type is not the generic type:
public static <T> Integer addAndReturn(T element, Collection<T> collection)
Generic methods, like any other method, can have any return type, including the generic type itself, any other class type, any basic or inherent data type, or void. You may be confusing 2 unrelated parts of the method signature, thinking they are dependent, when they are not. They are only "dependent" in the sense that if you do use T as the return type, the return value's type is of the generic type you provide at the call site.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With