如何在参数中获取Generic E的新实例

时间:2016-09-28 12:56:34

标签: java generics

我有一种方法可以加入2个(String, int, ...)数组 但我有一个问题。当我想创建一个长度为两个数组的数组时。

代码:

public static <E> E[] joinArray(E[] a, E[] b)
{
    a = (a != null) ? a : (E[]) new Object[0];
    b = (b != null) ? b : (E[]) new Object[0];
    int countBoth = a.length + b.length;
    int countA = a.length;
    E[] temp;
    try
    {
        temp = (E[]) new ????[countBoth] ;
       //(E[]) new String[countBoth];
    }
    catch (Exception e)
    {
        Log.i(LOG_TAG, "[8001] Error in joinArray() \r\n"+getExceptionInfo(e));
        e.printStackTrace();
        return null;
    }

    for (int i = 0; i < countA; i++)
        Array.set(temp, i, a[i]);

    for (int i = countA; i < countBoth; i++)
        Array.set(temp, i, b[i - countA]);

    return temp;
}

    String[] s1 = new String[]{"A","B","C"};
    String[] s2 = new String[]{"e","f",};
    String[] s3 = joinArray(s1,s2);

1 个答案:

答案 0 :(得分:0)

坦克为你的答案。 我在how to create a generic array in java

中得到了答案

Corect代码是:

public static <E> E[] joinArray(E[] a, E[] b)
{

    if(a == null && b == null)
        return null;
    if(a != null && b != null && a.getClass() != b.getClass())
        return null;

    E typeHelper = (a != null)? a[0] : b[0];
    a = (a != null) ? a : (E[]) new Object[0];
    b = (b != null) ? b : (E[]) new Object[0];
    int countBoth = a.length + b.length;
    int countA = a.length;
    E[] temp;

    try
    {
        Object o = Array.newInstance(typeHelper.getClass(), countBoth);
        temp = (E[]) o ;

        for (int i = 0; i < countA; i++)
            Array.set(temp, i, a[i]);

        for (int i = countA; i < countBoth; i++)
            Array.set(temp, i, b[i - countA]);
    }
    catch (Exception e)
    {
        Log.i(LOG_TAG, "[8001] Error in joinArray() \r\n"+getExceptionInfo(e));
        e.printStackTrace();
        return null;
    }

    return temp;
}