2016-01-11 62 views
1

我有一些Java 8代碼,如下面的代碼片段所示。Java:通用類型數組作爲函數參數

public class Test { 
    static protected <T extends Comparable<T>> T[] myFunction(T[] arr) { 
    // do stuff... 
    return arr; 
    } 

    public static void main(String[] args) { 
    int[] a = new int[] {1,4,25,2,5,16}; 
    System.out.println(Arrays.toString(myFunction(a))); 
    } 
} 

當我嘗試運行它,我得到的錯誤如下:

Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method myFunction(T[]) in the type LottoResult is not applicable for the arguments (int[])

爲什麼會出現這種情況?我怎麼也得重寫它能夠也通過int[]陣列myFunction

+1

int []是基元,T []期望非基元類型 – Aksiom

回答

9

一個數組T[]意味着當您傳遞一個基元數組(int[])時,該數組有一些引用類型T。這就是你得到編譯錯誤的原因。

爲了得到它的工作,你需要做的:

Integer[] a = new Integer[] {1,4,25,2,5,16}; 

這將創建一個引用類型(Integer[])的陣列,因爲自動裝箱會發生。