簡體   English   中英

為什么 google-collections 包含語義相同的功能和奇怪的 generics?

[英]Why google-collections contains semantically equal functions and strange generics?

為什么 google-collections 或 guava 包含語義相等的功能? 例子:

static
<T> Predicate<T>
and(Predicate<? super T>... components) 

static
<T> Predicate<T>
and(Predicate<? super T> first, Predicate<? super T> second) 

即可以接受幾個arguments的所有函數。

第二個問題為什么這些函數的定義使用泛型<? super T> <? super T>而不是<T>

要回答第一個問題,可變參數版本( Predicate<? super T>... )會在使用多個泛型謂詞(例如Predicate<T> )調用時警告您未檢查創建泛型數組。 對於組合兩個謂詞的常見情況,您不會收到該警告。

要回答第二個問題,請使用Predicate<? super T> Predicate<? super T>意味着您可以在調用創建Predicate<Integer>的方法時傳入Predicate<Object> (或Predicate<Number>或其他)。 例如,如果Predicates.notNull()Predicate<Object> (應該是這樣)並且您想將它和一些Predicate<Integer>結合起來,如果 arguments 被要求是Predicate<T>

我相信,第一部分是為了性能。

在第二部分它必須是<? super T> <? super T> ,因為 Guava 允許您放入任何可以在任何超類型 T 和 T 本身上評估的 Predicate 。 不僅是 T 本身,就像<T>一樣。 這是有道理的,因為特定的 Predicate 可能更通用,因此定義在更通用的類型上,但您希望將其與某些子類型一起使用。

您會看到與 TreeSet 構造函數相同的內容: TreeSet(Comparator<? super E> c)

另請查看Generics 教程第 18 頁

暫無
暫無

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

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