Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generic return object

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> ?
like image 720
saurabh ranu Avatar asked Jan 18 '12 19:01

saurabh ranu


2 Answers

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).

like image 81
NPE Avatar answered Sep 24 '22 07:09

NPE


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.

like image 41
Óscar López Avatar answered Sep 22 '22 07:09

Óscar López