1

so, as per the question, I have this code in Java:
public class example {
    static ArrayList<String[]> test = new ArrayList<String[]>();
    private String[] a = {"this", "is,", "a test"};
    private String[] b = {"Look", "a three-headed", "monkey"};

    public void fillTest() {
        test.add(a);
        test.add(b);
        // so far so good, I checked this method
        // with a System.out.print and it works
    }

    // later in the code I have a method that try
    // to take the arrayList test and copy it into
    // a String[] named temp. In my vision temp
    // should than be accessed randomly by the
    // method itself and the content printed out
    // from temp should be removed from test -
    // that's why I'm using an ArrayList

    public void stuff() {
        // some stuff
        // runtime error happens here:
        String[] temp = test.toArray(new String[test.size()]);
        // other stuff that never made it to runtime
    }
}

The problem is that while the compiler has nothing against this, at Runtime I get this error:

Exception in thread "main" java.lang.ArrayStoreException: arraycopy: element type mismatch: can not cast one of the elements of java.lang.Object[] to the type of the destination array, java.lang.String

I can't understand the reason behind - looks to me like I'm asking it to fill an Array of Strings with strings, so why the error?

Agricolo
  • 53
  • 8

2 Answers2

4

You are trying to convert a List whose elements are arrays of String to an array whose elements are Strings. This doesn't work, since an array of String is not a String.

Instead, you can convert your List of arrays to a 2D array of Strings:

String[][] temp = test.toArray(new String[test.size()][]);

If you want to put all the elements of the String arrays of the List in a single array of String, you have to do some processing. With Streams it can be done with:

String[] temp = test.stream().flatMap(Arrays::stream).toArray(String[]::new);
Eran
  • 359,724
  • 45
  • 626
  • 694
0

You can use Stream.flatMap method to flatten this list of arrays of strings and get a stream over a single array of strings. And then you can get an array containing the elements of this stream:

List<String[]> test = Arrays.asList(
        new String[]{"this", "is,", "a test"},
        new String[]{"Look", "a three-headed", "monkey"});

String[] temp = test
        // return Stream<String[]>
        .stream()
        // return Stream<String>
        .flatMap(arr -> Arrays.stream(arr))
        // return an array of a specified size
        .toArray(size -> new String[size]);

System.out.println(Arrays.toString(temp));
// [this, is,, a test, Look, a three-headed, monkey]

See also: Is there any way to convert a 2D List to 1D List using only 'map' not using 'flatMap'?