0

I'm trying to create a generic method that will concatenate 2 arrays (of any type, as long as it's the same between the two). I have created a method that does not produce errors in the IDE, but when I actually use it to try to concatenate 2 String arrays, I get the error that an Object [] cannot be cast to a String []. I understand this error as I've had it before in another program. The only way to fix it, as far as I know, is to create a new array of the type you want, then iterate through the object array and individually cast all the objects to the type you want. Is there a better way to cast the array than that using a method like mine?
This is my method:

public static <T> T [] concatArrays(T [] a1, T [] a2)
{
    @SuppressWarnings("unchecked")
    T [] both = (T[]) new Object [a1.length + a2.length];

    for(int i = 0; i < a1.length; i++)
        both[i] = a1[i];

    for(int i = 0; i < a2.length; i++)
        both[i + a1.length] = a2[i];

    return both;
}

This was my first time ever really working with full generic types so I have no idea if I did this right.

StrongJoshua
  • 975
  • 10
  • 24
  • I'm assuming you're assigning the return value to a variable of type `String[]`. Is this right? What is the type of the array returned? Are those compatible? – Sotirios Delimanolis Jul 10 '14 at 15:40
  • @SotiriosDelimanolis Yes, the returned array is assigned to a `String[]`. The two arrays I pass in are both `String[]`s as well. When I hover over the method call in Eclipse, it automatically completes the generic types and shows that the returned array should be of type `String[]` – StrongJoshua Jul 10 '14 at 15:45
  • To explain the reason for your issue, you create a `Object[]` inside your method but when you return it, you try to assign it to a `String[]`. An `Object[]` **is not** a `String[]`. – Sotirios Delimanolis Jul 10 '14 at 15:51
  • 2
    @StrongJoshua You may find [this](http://stackoverflow.com/questions/11173580/how-to-create-array-of-generic-type) question useful. – GriffeyDog Jul 10 '14 at 15:55
  • 1
    @StrongJoshua in addition to GriffeyDog's comment, This [link](http://stackoverflow.com/questions/212805/in-java-how-do-i-dynamically-determine-the-type-of-an-array) is to get the type of array. – Wundwin Born Jul 10 '14 at 16:05
  • @GriffeyDog Thanks for sending me that link, I didn't know about that method! – StrongJoshua Jul 10 '14 at 16:07
  • @suninsky Thanks for linking me that, it allows me to keep the method without adding parameters. – StrongJoshua Jul 10 '14 at 16:07

0 Answers0