[英]Why can't a Generic type containing a Generic type be assigned to a Generic typed class of wildcard type
抱歉,標題似乎令人困惑,但請按順序排列一些示例。
假設我有一些帶有通用類型參數的Java類:
public class GenericClass<T> {
}
我可以創建一個類型為存儲對象的變量,並將通用參數設置為String
。 Java還可以讓我將該變量分配給另一個變量,但將通用參數設置為通配符<?>
類型:
GenericClass<String> stringy = ...
GenericClass<?> generic = stringy; // OK
但是,在使用具有泛型參數的類時,如果將該參數的類型設置為泛型,則無法將該類的對象分配給相同類型/泛型的類型,后者(內部/嵌套)參數的通配符類型為<?>
:
GenericClass<GenericClass<String>> stringy = ...
GenericClass<GenericClass<?>> generic = stringy; // Compile Error
// And just in case that is confusing, a more
// realistic example involving Collections:
List<GenericClass<String>> stringy = ...
List<GenericClass<?>> generic = stringy; // Compile Error
具體的編譯錯誤是:
Type mismatch: cannot convert from List<GenericClass<String>> to List<GenericClass<?>>
憑直覺,我認為所討論的作業應該不是問題。 那么為什么這個分配有問題呢?
您面臨的問題稱為協方差 。
List<GenericClass<String>> stringy = ...
List<GenericClass<?>> generic = stringy;
generic.add(new GenericClass<Integer>());
如果這不是編譯錯誤,那么最后一行代碼將是可能的。
您可以通過以下方法解決錯誤:
List<? extends GenericClass<?>> generic = stringy;
但是您也不能使用add
因為您真的不知道什么? extends GenericClass<?>
? extends GenericClass<?>
為(再次是協方差)。 在這種情況下,您只能枚舉List並期望GenericClass<?>
。
從技術上講,這是因為List<GenericClass<String>>
不是List<GenericClass<?>>
的子類型。 為了使其正常工作,您可以執行以下操作
List<? extends GenericClass<?>> generic = stringy
應該可以按預期工作(盡管很丑...)。
例如,請參閱此SO問題以獲取更多詳細信息
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.