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.