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]