簡體   English   中英

Java泛型中的上限通配符

[英]Upper bound wildcard in Java Generics

經過一段時間的搜索后,我仍然無法找到我的問題的任何答案,即使有幾個與泛型有關的話題,所以在這里你走了:

ArrayList<? super IOException> list = new ArrayList<Exception>();
list.add(new FileNotFoundException("this is ok."));
list.add(new IOException("This is ok"));
list.add(new ClassCastException("compile err"));//why compile err?
list.add(new Exception("compile err"));//why compile err? 

為什么最后兩行不能編譯? 特別是最后一行。 我一直在對這個話題進行相當多的測試,但仍然無法理解邏輯。

謝謝。

ArrayList<? super IOException> ArrayList<? super IOException>可能是以下任何一個(因為有一個外卡):

ArrayList<IOException>
ArrayList<Exception>
ArrayList<Throwable>
ArrayList<Object>

代碼需要處理所有四種可能性。

但是如果它是一個ArrayList<IOException> ,則不能放入ClassCastExceptionException ,因此編譯錯誤。

這是我沒有得到的:為什么這個編譯------ >>> list.add(new FileNotFoundException(“this is ok。”)); <<< ----我認為FileNotFoundException也低於IOException的界限。 但它編譯得很好。

不,FileNotFoundException沒問題,因為它擴展了IOException,你可以把它放在所有四種類型的列表中。

請注意,由於歷史原因,數組不會獲得相同的嚴格類型檢查,您可以編譯以下內容(然后在運行時獲取數組存儲異常):

   Exception[] a = new IOException[4];
   a[0] = new FileNotFoundException("this is ok.");  
   a[1] = new IOException("This is ok");
   a[2] = new ClassCastException("compiles, but boom!");
   a[3] = new Exception("compiles, but boom!"); 

考慮相同的list聲明,但使用不同的賦值:

ArrayList<? super IOException> list = new ArrayList<IOException>();

list類型沒有變化,但現在添加ClassCastExceptionException顯然是錯誤的。

對我來說,這指的是較低的通配符: <? super IOException> <? super IOException> 上邊界的通配符將是<? extends IOException> <? extends IOException>

示例中的通配符似乎僅在將新Object分配給變量的行中有效。 以后訪問時,顯然不再有效。 然后它與ArrayList<IOException>相同。

所以你對自己的解釋顯然是錯誤的。 上限和下限意味着它所說的。

Exception是超類,因為IOException 擴展了 Exception 你可以使用:

 List<Exception> list = new ArrayList<Exception>();
 list.add(...); // any exception

然后它將編譯所有異常類型。

我認為因為異常的最后一個不是從基類IOException派生的

根據您的ArrayList引用泛型聲明,您只能添加實際的IOException(因為?super)或將IOException擴展到列表中的對象。

ClassCaseException和Exception不是從IOException派生的,因此它失敗了。

暫無
暫無

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

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