Reputation: 7458
I was reading about Set interface from here which the code sipped below which is a generic method that removes duplicates from a collection.
My question is what is that **< E>**
placed after static before Set<E>
?
I mean wouldn't that Set<E>
be enough ? why <E>
was there twice?
public static <E> Set<E> removeDups(Collection<E> c) {
return new LinkedHashSet<E>(c);
}
Upvotes: 0
Views: 133
Reputation: 121710
This means that this method declares a generic parameter type which the class does not define; in this case, you MUST declare the parameter type before the return type (even if this "return type" is void
).
Think about it this way. Remove the initial <E>
. Your declaration would then become:
public static Set<E> removeDups(Collection<E> c)
What is E
here? Unless it is a generic parameter type defined by the class itself, it can only be an existing class.
Hence this syntax. It allows you to define a generic parameter for use in the method signature.
Upvotes: 1
Reputation: 2866
Here **<E>**
is a generic type. Generic type is defined as
A generic type is a generic class or interface that is parameterized over types. The following Box class will be modified to demonstrate the concept. LINK
And regarding you question related to <E>
. A good description for it can be found on the same tutorial
Type Parameter Naming Conventions
By convention, type parameter names are single, uppercase letters. This stands in sharp contrast to the variable naming conventions that you already know about, and with good reason: Without this convention, it would be difficult to tell the difference between a type variable and an ordinary class or interface name.
The most commonly used type parameter names are:
E - Element (used extensively by the Java Collections Framework)
K - Key
N - Number
T - Type
V - Value
S,U,V etc. - 2nd, 3rd, 4th types
You'll see these names used throughout the Java SE API and the rest of this lesson.
Upvotes: 1
Reputation: 361
It's just the generic type used within the method. Static methods that use generic types must specify that type before the return type.
Upvotes: 0