簡體   English   中英

Java 通用符號,<e> 放<e></e></e>

[英]Java generic notation, <E> Set <E>

以下 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>Set<E>類型的一部分,它是方法的返回類型:它是一個Set ,其元素的類型為E ,並且可以添加E s。

在方法上聲明一個或多個類型變量會使該方法成為泛型方法 實例方法可以從周圍的class中訪問類型變量,或者聲明自己的; static 方法不能訪問來自周圍 class 的類型變量,因此必須始終聲明自己的。

// 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) {

您可以將其解讀為:無論 'E' 是什么(對於任何類型 'E'),傳遞 4 個此類型的參數並得到一個此類型的 Set 作為結果。

您的方法是static 它將無法訪問從其 class 聲明的類型變量,因此它需要聲明自己的<type>聲明。 所以它不是雙重聲明。

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. 

如果您的非 static 方法使用由 class 聲明的相同通用<type> ,則不需要使用這種聲明。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM