Java 泛型表示法, <E> 设置<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,并且可以向其添加Es。

在方法上声明一个或多个类型变量会使该方法成为泛型方法。实例方法可以从周围的类访问类型变量,并可以在需要时声明自己的附加变量;静态方法无法访问周围类的类型变量,因此必须始终声明自己的类型变量。

// 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个参数,并得到一个这种类型的集合。

你的方法是static.它无法访问从其类声明的类型变量,因此需要声明自己的<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. 

如果您的非静态方法使用类声明的相同泛型<type>则无需使用此类声明。

最新更新