Dear all,
I am just reading through collection java tutorial and wondering why the <E>
is needed after static?
public static<E> Set<E> removeDups(Collection<E> c) { return new LinkedHashSet(c); }
Thanks, Sarah
Dear all,
I am just reading through collection java tutorial and wondering why the <E>
is needed after static?
public static<E> Set<E> removeDups(Collection<E> c) { return new LinkedHashSet(c); }
Thanks, Sarah
The <E>
is the way of declaring that this is a Generic Method a feature introduced with Generics in Java 5.0
See here for more details about its usage and rationale.
For readability, there's usually a space between the static and the generic parameter name. static
declares the method as static, i.e. no instance needed to call it. The <E>
declares that there is an unbounded generic parameter called E that is used to parameterize the method's arguments and/or return value. Here, it's used in both the return type, Set<E>
to declare the method returns a Set of E, and in the parameter, Collection<E>
indicating that the method takes a collection of E.
The type of E is not specified, only that the return value and the method parameter must be generically parameterized with the same type. The compiler determines the actual type when the method is called. For example,
Collection<String> myStrings = new ArrayList<String>();
.. add strings
Set<String> uniqueStrings = SomeClass.removeDups(myStrings);
If you attempt use different parameterized types for the two collections, such as
Set<Integer> uniqueStrings = SomeClass.removeDups(myStrings);
this will generate a compiler error, since the generic parameters do not match.