The following Java code is used to create a set in Java:
Set<String> fromUi = Set.of("val1", "val2", "val3", "val4");
Which in term calls this code:
static <E> Set<E> of(E e1, E e2, E e3, E e4) {
return new ImmutableCollections.SetN<>(e1, e2, e3, e4);
}
What does the "double" use of the type parameter mean? ie can we not just say Set<E>
instead of <E> Set<E>
?
can we not just say
Set<E>
instead of<E> Set<E>
?
No, because then the type variable E
wouldn't be declared.
This isn't a "double" use:
<E>
is the type variable declaration<E>
is part of the type of the Set<E>
which is the return type of the method: it's a Set
whose elements are of type E
, and to which E
s can be added.Declaring one or more type variables on a method makes the method a generic method . Instance methods can access type variables from the surrounding class, or declare their own; static methods cannot access type variables from the surrounding class, and so must always declare their own.
// 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) {
You can read it as: whatever 'E' is (for any type 'E'), pass 4 parameters of this type and get a Set of this type as a result.
Your method is static
. It won't be able to access type variables declared from its class, hence it needs to declare its own <type>
declaration. So its not double declaration.
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.
you won't need to use this kind of declaration if your non static method uses same generic <type>
declared by class.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.