2017-06-01 55 views
0

是否可以對不同的數據類型重用相同的函數? 所以,比如我有,如果我想這樣做有一個字節的ArrayList我必須這樣做對多種數據類型使用相同的函數

public static byte[] arrayListToByteArray(ArrayList<Byte> list) { 
    byte[] out = new byte[list.size()]; 
    int count = 0; 
    for (byte x : list) { 
     out[count] = x; 
     count++; 
    } 
    return out; 
} 

所以我是一個整數的ArrayList轉換成整數數組

public static int[] arrayListToIntArray(ArrayList<Integer> list) { 
    int[] out = new int[list.size()]; 
    int count = 0; 
    for (int x : list) { 
     out[count] = x; 
     count++; 
    } 
    return out; 
} 

但是功能想知道是否有更好的方法,而不僅僅是用不同的數據類型重複相同的代碼,並且基本上具有整個類的相同代碼?或者我可以做些什麼,以便它可以用於所有數據類型?

+1

若你想從包裝器中返回原始類型。如果你不介意返回一個'Byte []'或'Integer []',那麼你可以直接調用'list.toArray();' –

+0

這只是我使用的一個例子,並非特定於該函數,但無論如何感謝。 – Nightfortress

+0

是的,一般出於性能和Java-y的原因,你不想爲原始類型做這件事。最好將Java分成基於原始/數組的東西以及基於對象/泛型的東西。你可以使用Number.class來解決這個問題,但是有一些原因,如流和函數的原始版本。如果你來自C#,這是一個重大的差異。 – Novaterata

回答

3

是的,你可以。它被稱爲Generics

public static <T> T[] arrayListToIntArray(ArrayList<T> list) { 
    T[] out = (T[]) new Object[list.size()]; 
    int count = 0; 
    for (T x : list) { 
     out[count] = x; 
     count++; 
    } 
    return out; 
} 

更新:

你不能實例化一個泛型類型,所以你也可以通過另一種說法,這將是類型,看看this

public static <T> T[] arrayListToIntArray(ArrayList<T> list, Class<T> t) { 
     T[] out = (T[]) Array.newInstance(t, list.size()); 
     int count = 0; 
     for (T x : list) { 
      out[count] = x; 
      count++; 
     } 
     return out; 
    } 
+0

您能解釋爲什麼我在該代碼中出現「非法啓動類型」錯誤? – Nightfortress

+0

我更新了答案。看一看,讓我知道。 – epinal

+0

它解決了你的問題嗎?如果確實如此,請將答案標記爲解決方案,或者如果您有更多問題,請告訴我。謝謝@Nightfortress – epinal

1

改變你的方法泛型打字,你可以寫這個

public static <T> T[] arrayListToArray(ArrayList<T> list, Class<T> type) { 
    @SuppressWarnings("unchecked") 
    final T[] out = (T[]) Array.newInstance(type, list.size()); 
    int count = 0; 
    for (T x : list) { 
     out[count] = x; 
     count++; 
    } 
    return out; 
} 

,然後使用它像這樣

public static void main(String[] args) { 
    ArrayList<Integer> intList = new ArrayList<>(); 
    intList.add(13); 
    intList.add(37); 
    intList.add(42); 
    Integer[] intArray = arrayListToArray(intList, Integer.class); 

    ArrayList<Byte> byteList = new ArrayList<>(); 
    byteList.add((byte) 0xff); 
    byteList.add((byte) 'y'); 
    byteList.add((byte) 17); 
    Byte[] byteArray = arrayListToArray(byteList, Byte.class); 

    System.out.println(Arrays.toString(intArray)); 
    System.out.println(Arrays.toString(byteArray)); 
} 

輸出:

[13, 37, 42] 
[-1, 121, 17] 
相關問題