2017-08-10 91 views
1

的給定類型:什麼爲T

public static <T> void copy(List<? super T> dest, List<? extends T> src) 

我看到這個頁面: Confusion over Java generic method type inference

但我仍然困惑,dasblinkenlight說,只要對象傳遞中是一致的,然後代碼應該編譯。

這是否意味着第一個參數類型將有助於確定第二個有效的 ?

public class Hello { 

    public static void main(String[] args){ 
     ArrayList<Animal> dogs = new ArrayList<>(); 
     ArrayList<Marly> marlies = new ArrayList<>(); 

     copy(dogs,marlies); 
    } 

    public static <T> void copy(List<? super T> dest, List<? extends T> src{ 

    } 
} 

class Animal{} 
class Dog extends Animal { } 
class Beagle extends Dog { } 
class Marly extends Beagle{ } 

幾乎所有可能的方法我都圍繞它編譯,只要首先是在繼承層次更高的這兩個列表改變。

有人可以幫助解釋遠一點

+0

沒有這個職位澄清一點? https://stackoverflow.com/questions/1368166/what-is-a-difference-between-super-e-and-extends-e – csunday95

+0

明白了。所以我認爲在這樣的情況下確實沒有T,並且真正重要的是方法體中會發生什麼以及如何將這些類相互關聯是正確的。 – madmax

回答

0

的方法簽名使用兩種不同的通配符:

  • <? super T>
  • <? extends T>

差異說明如下:Difference between <? super T> and <? extends T> in Java

每次調用此方法時,java編譯器都會嘗試查找T,以使兩個參數都滿足其條件。看起來有多種選擇時,編譯器會選擇最具體的T。

所以

// fails because there is no superclass of Dog that is a subclass of Animal 
copy(new ArrayList<Dog>(), new ArrayList<Animal>()) 
// chooses T = Marly because it is most specific solution 
copy(new ArrayList<Animal>(), new ArrayList<Marly>()) 
相關問題