Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
279 views
in Technique[技术] by (71.8m points)

Java generic notation, <E> Set <E>

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? i.e can we not just say Set<E> instead of <E> Set<E>?

question from:https://stackoverflow.com/questions/66050803/java-generic-notation-e-set-e

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:

  • The first <E> is the type variable declaration
  • The second <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 Es 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() { ... } 
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...