Why is there an extra <E> in this generic method?
In <E> List<E>
, the first <E>
denotes that E
is a type parameter. If you hadn't specified it, then Java would think the E
in E value
referred to an actual class named E
, and ask you to import it. See generic methods.
You use the <E>
to typify the method you are defining.
The most common example of generics is to have a typified class like this:
public class SomeClass<E> {
...
}
Then, when you are creating a new object of that class you define the type directly like this:
new SomeClass<String>();
That way any method in that class that refers to <E>
, will treat <E>
as a String, for that instance.
Now consider a static method (which is not bound to any particular instance of a class), in order to typify that method you have use another kind of typification which applies to methods, like this:
static <E> List<E> nCopies(int n, E value)
You use the <E>
before the return type to say "this particular method will consider some E when it executes". What <E>
will be is decided when you invoke the method:
nCopies(3, "a");
In this example <E>
will be a String, so the return type will be a List<String>
.
Finally, you can even mix them both:
public class SomeClass<E> {
public <F> void doSomething(E e, F f) {
...
}
}
In this case, if you have an instance of SomeClass, the E in the doSomething method will always be String (for that instance), but the F can be anything you want it to be.