Search code examples
javagenericscastingapache-commonsserializable

How to convert Serializable in an array of String?


I wanted to join some string arrays into one. And i used ArrayUtils.addAll(T[], T...) i found on some answers here. As it is described there, i should just cast it to a String array. When i try to do it, it shows me this error

Cannot store java.io.Serializable in an array of java.lang.String at org.apache.commons.lang3.ArrayUtils.addAll

My code is here

String[] splitLeft=split(left);
String[] middle=new String[]{with};
String[] splitRight=split(right);

String[] inWords=(String[])ArrayUtils.addAll(splitLeft,middle,splitRight);

What is the problem, and how can i fix this?

Ps: with is just a string.


Solution

  • The problem here is that the signature of the method is:

        addAll(T[] array1, T... array2)
    

    so the second and third parameters are being treated as single elements of array2: they are not concatenated; as such, the inferred type is Serializable, which is the least upper bound of String (the element type of the first parameter) and String[] (the element type of the varargs).

    Instead, you'll have to join them in multiple calls, if you're going to do it with ArrayUtils.addAll:

    addAll(addAll(splitLeft, middle), splitRight)
    

    Alternatively, you can just build the concatenated array in a small number of statements:

    // Copy splitLeft, allocating extra space.
    String[] inWords = Arrays.copyOf(splitLeft, splitLeft.length + 1 + splitRight.length);
    
    // Add the "with" variable, no need to put it in an array first.
    inWords[splitLeft.length] = with;
    
    // Copy splitRight into the existing inWords array.
    System.arraycopy(splitRight, 0, inWords, splitLength.length + 1, splitRight.length);