can we not just say Set<E>
instead of <E> Set<E>
?
No, because then the type variable E
wouldn't be declared.
This isn't a "double" use:
- The first
<E>
is the type variable declaration
- The second
<E>
is part of the type of the Set<E>
which is the return type of the method: it's a Set
whose elements are of type E
, and to which E
s can be added.
Declaring one or more type variables on a method makes the method a generic method. Instance methods can access type variables from the surrounding class, or declare their own; static methods cannot access type variables from the surrounding class, and so must always declare their own.
// Generic class, E is accessible in instance methods/initializers/constructors.
class MyClass<E> {
// Non-generic method, uses the E from the class.
Set<E> someSet() { ... }
// Generic method, declares its own type variable.
<M> Set<M> someSet1() { ... }
// Generic method, declares its own type variable which hides
// the E on the class (bad idea).
<E> Set<E> someSet2() { ... }
// Generic method, must declare its own type variable.
static <E> Set<E> someStaticSet() { ... }
}
// Non-generic classes can declare generic methods.
class MyClass {
// Generic method, declares its own type variable.
<M> Set<M> someSet1() { ... }
// Generic method, must declare its own type variable.
static <E> Set<E> someStaticSet() { ... }
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…