簡體   English   中英

枚舉之間的區別<!--? extends ZipEntry-->和枚舉<zipentry> ?</zipentry>

[英]Difference between Enumeration<? extends ZipEntry> and Enumeration<ZipEntry>?

枚舉<? 擴展 ZipEntry> 和 Enumeration<ZipEntry>? 如果是這樣,有什么區別?

當您擁有其中一個時,您可以做什么並沒有實際區別,因為類型參數僅用於“輸出”position。 另一方面,在您可以用作其中之一方面存在很大差異。

假設您有一個Enumeration<JarEntry> - 您不能將它傳遞給將Enumeration<ZipEntry>作為其 arguments 之一的方法。 可以將其傳遞給采用Enumeration<? extends ZipEntry> 雖然Enumeration<? extends ZipEntry>

當你有一個在輸入和 output 位置都使用類型參數的類型時更有趣 - List<T>是最明顯的例子。 以下是三個參數變化的方法示例。 在每種情況下,我們都會嘗試從列表中獲取一個項目,然后添加另一個。

// Very strict - only a genuine List<T> will do
public void Foo(List<T> list)
{
    T element = list.get(0); // Valid
    list.add(element); // Valid
}

// Lax in one way: allows any List that's a List of a type
// derived from T.
public void Foo(List<? extends T> list)
{
    T element = list.get(0); // Valid
     // Invalid - this could be a list of a different type.
     // We don't want to add an Object to a List<String>
    list.add(element);   
}

// Lax in the other way: allows any List that's a List of a type
// upwards in T's inheritance hierarchy
public void Foo(List<? super T> list)
{
    // Invalid - we could be asking a List<Object> for a String.
    T element = list.get(0);
    // Valid (assuming we get the element from somewhere)
    // the list must accept a new element of type T
    list.add(element);
}

有關更多詳細信息,請閱讀:

是的,直接來自太陽 generics 教程之一:

這里的 Shape 是一個抽象的 class 具有三個子類:圓形、矩形和三角形。

 public void draw(List<Shape> shape) { for(Shape s: shape) { s.draw(this); } }

值得注意的是,draw() 方法只能在 Shape 列表上調用,而不能在例如 Circle、Rectangle 和 Triangle 列表上調用。 為了讓該方法接受任何類型的形狀,它應該寫成如下:

 public void draw(List<? extends Shape> shape) { // rest of the code is the same }

現在你剛剛離開並讓我想起了我希望我們在 C# 世界中結束的事情。

Other than the links provided, there's some good links about C# and Java in relation to this topic in the answers to this question: Logic and its application to Collections.Generic and inheritance

其中的一個選擇是:

暫無
暫無

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

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