2016-03-23 187 views
0
class GenMethDemo { 
    static <T, V extends T> boolean isIn(T x, V[] y) { 
     for (int i = 0; i < y.length; i++) 
      if (x.equals(y[i])) 
       return true; 
     return false; 
    } 

    /*when compiled in java 7 it producing an error and compiling in java 8 without error */ 
    public static void main(String args[]) { 
     Integer nums[] = {1, 2, 3, 4, 5}; 
     String s[] = {"one", "two", "three"}; 
     System.out.println(isIn("fs", nums)); 
     /* 
     when compiled in java 7 it producing an error and compiling in java 8 without error */ 
    } 
} 
+3

請編輯您的問題,以顯示*文本*描述問題。特別是,你在Java 7中遇到什麼錯誤? –

+0

'isIn(「fs」,nums)''不應該工作,因爲在這種情況下'T'將是'String'並且'V'將是'Integer',它不會擴展'String'。然而,Java 8類型推斷可能會比較寬鬆,因爲它試圖找到一個匹配,即'T = Object'和'V = Object'。 – Thomas

回答

1

這是由於Java 8中的通用目標類型推理改進。實際上,我回答了類似於上週的問題。 Java 8 call to generic method is ambiguous

問題的第一個答案Java 8: Reference to [method] is ambiguous也很好。

Java 8能夠推斷傳遞給泛型方法的參數類型。正如@Thomas在他的評論中所說的那樣,T被推斷爲Object,並且V被推斷爲是Object的對象,因此Integer。在Java 7中,這隻會引發錯誤,因爲Integer顯然不會延伸String

0

在Java 7類型推斷中將會看到T = StringV = Integer,這將不會滿足V extends T

然而,JLS對Java 8所指出,這會工作:

List<Number> ln = Arrays.asList(1, 2.0); 

因此,在你的情況,這將被解析爲T = V = Object