[英]Java generic notation, <E> Set <E>
以下 Java 代码用于在 Java 中创建集合:
Set<String> fromUi = Set.of("val1", "val2", "val3", "val4");
术语称为此代码:
static <E> Set<E> of(E e1, E e2, E e3, E e4) {
return new ImmutableCollections.SetN<>(e1, e2, e3, e4);
}
类型参数的“双重”使用是什么意思? 即我们不能只说Set<E>
而不是<E> Set<E>
吗?
我们不能只说
Set<E>
而不是<E> Set<E>
吗?
不,因为那时类型变量E
不会被声明。
这不是“双重”用途:
<E>
是类型变量声明<E>
是Set<E>
类型的一部分,它是方法的返回类型:它是一个Set
,其元素的类型为E
,并且可以添加E
s。在方法上声明一个或多个类型变量会使该方法成为泛型方法。 实例方法可以从周围的class中访问类型变量,或者声明自己的; static 方法不能访问来自周围 class 的类型变量,因此必须始终声明自己的。
// 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() { ... }
}
static <E> Set<E> of(E e1, E e2, E e3, E e4) {
您可以将其解读为:无论 'E' 是什么(对于任何类型 'E'),传递 4 个此类型的参数并得到一个此类型的 Set 作为结果。
您的方法是static
。 它将无法访问从其 class 声明的类型变量,因此它需要声明自己的<type>
声明。 所以它不是双重声明。
The first <E> is where static method declares which type it uses
The second with Set<E> to specify the type of elements in a Set.
如果您的非 static 方法使用由 class 声明的相同通用<type>
,则不需要使用这种声明。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.