2

I have a method to join 2 arrays of (String, int, ...) but I have a problem. When I want to create an array with length of both arrays.

Code:

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);
px06
  • 1,990
  • 1
  • 19
  • 40
Ali Bagheri
  • 1,866
  • 19
  • 21

1 Answers1

0

Tanks for your answer. I get my answer in how to create a generic array in java

Corect code is:

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;
}
Community
  • 1
  • 1
Ali Bagheri
  • 1,866
  • 19
  • 21