Java通用表示法,Set
以下Java代码用于在Java中创建集合:Java通用表示法,Set,java,generics,Java,Generics,以下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
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);
}
双重使用类型参数意味着什么?i、 我们不能只说集合而不是集合吗
您可以将其理解为:无论“E”代表任何类型的“E”,传递该类型的4个参数,并获得一组该类型的结果
您可以将其理解为:无论“E”代表任何类型的“E”,传递该类型的4个参数,并获得一组该类型的结果
我们不能只说Set而不是Set吗
不,因为这样就不会声明类型变量E
这不是双重用途:
第一个是类型变量声明
第二个是集合类型的一部分,它是方法的返回类型:它是一个集合,其元素类型为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() { ... }
}
我们不能只说Set而不是Set吗
不,因为这样就不会声明类型变量E
这不是双重用途:
第一个是类型变量声明
第二个是集合类型的一部分,它是方法的返回类型:它是一个集合,其元素类型为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() { ... }
}
您的方法是静态的。它将无法访问从其类声明的类型变量,因此需要声明自己的声明。
所以这不是双重声明
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.
如果非静态方法使用由类声明的相同泛型,则不需要使用此类声明。您的方法是静态的。它将无法访问从其类声明的类型变量,因此需要声明自己的声明。
所以这不是双重声明
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.
如果非静态方法使用由类声明的相同泛型,则不需要使用此类声明。Read;是泛型类型声明,Set是方法的返回类型;是泛型类型声明,Set是方法的返回类型。