首页 > 解决方案 > Java 通用表示法,

问题描述

以下 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>吗?

标签: javagenerics

解决方案


我们不能只说Set<E>代替<E> Set<E>吗?

E不,因为这样就不会声明类型变量。

这不是“双重”用途:

  • 首先<E>是类型变量声明
  • 第二个<E>是 the 类型的一部分,Set<E>它是方法的返回类型:它是 a ,它的Set元素是 type E,并且E可以添加 s 。

在方法上声明一个或多个类型变量会使该方法成为泛型方法。实例方法可以访问周围类的类型变量,也可以声明自己的;静态方法不能访问周围类的类型变量,因此必须始终声明它们自己的。

// 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() { ... } 
}

推荐阅读