java - 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>
吗?
解决方案
我们不能只说
Set<E>
代替<E> Set<E>
吗?
E
不,因为这样就不会声明类型变量。
这不是“双重”用途:
- 首先
<E>
是类型变量声明 - 第二个
<E>
是 the 类型的一部分,Set<E>
它是方法的返回类型:它是 a ,它的Set
元素是 typeE
,并且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() { ... }
}
推荐阅读
- c# - MathNet.Numerics 库是否支持 SIMD?
- matlab - 如何计算 (hh:mm:ss + minutes()) 并在 MATLAB GUI 表中显示所有结果?
- react-native - 如何在不使用数据状态的情况下使用 FlatList
- react-native - React-Native 使用 Jest 测试 AppState
- android - 有没有办法使用 Firebase App Distribution 为每个 Android 构建变体配置单独的 serviceCredentialsFile?
- swagger - 使用 springdoc-openapi 接受标头的默认值
- linux - 如何将脚本中的文本保存到linux中另一个脚本的变量中?
- python - 根据 pandas DataFrame 中的一个或多个参数添加总和的函数
- imagemagick - libMagickCore-6.Q16.so.2:无法打开共享对象文件
- php - 在 Laravel 5.8 的 PHPWord 中生成 Word 文件