2016-09-28 5 views
2

Ich habe eine Methode, 2 Arrays von (String, int, ...) zu verbinden, aber ich habe ein Problem. Wenn ich ein Array mit der Länge beider Arrays erstellen möchte.Wie bekomme ich neue Instanz von Generic E in Parameter

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); 
+7

Mögliches Duplikat von [Wie ein generisches Array in Java erstellen?] (Http://stackoverflow.com/questions/529085/how- to-create-a-generic-array-in-java) – fabian

+1

versuche dies: 'temp = (E []) neues Objekt [countBoth]' –

+1

Arrays und Generika vermischen sich nicht. Tun Sie sich selbst einen Gefallen und benutzen Sie Listen. – VGR

Antwort

0

Tanks für Ihre Antwort. ich meine Antwort in how to create a generic array in java

Corect Code ist:

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; 
} 
Verwandte Themen