Recently I was reading the following piece of code from oracle collection tutorial when i came across this piece of code.
public static <E> Set<E> removeDups(Collection<E> c) {
return new LinkedHashSet<E>(c);
}
I was not able to understand why the returned value is something
<E> Set<E> and not just Set<E> ?
The return type is, in fact, simply Set<E>
.
The other <E>
is there to indicate that this is a generic method, and to state that E
is a parameter to the generic. Without this <E>
, the compiler would assume that E
is an existing class, and would try to locate it (producing an error if no class named E
is in scope).
It is just Set
, a set with elements of type E
to be more precise. The extra <E>
in front of the return type is the type declaration for that method, specifying that the type <E>
is to be used only in the scope of this particular method - not to be confused with a class' type parameter, like this one:
public class Example<E> {
In the above snippet, the type parameter <E>
is visible for all the methods in the class, whereas a type declaration like the one in your question, is visible only in that method.
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