Fill an Array with generic Lists using supplier in Java 8 throws ClassCastEx b/c of type erasure Fill an Array with generic Lists using supplier in Java 8 throws ClassCastEx b/c of type erasure arrays arrays

Fill an Array with generic Lists using supplier in Java 8 throws ClassCastEx b/c of type erasure


The Stream generator still generates the objects you want, the only problem is calling toArray() will give you back an object array, and you can't downcast from an Object array to a sub object array (since you've got something like: Object[] { ArrayList, ArrayList }).

Here is an example of what is happening:

You think you have this:

    String[] hi = { "hi" };    Object[] test = (Object[]) hi; // It's still a String[]    String[] out = (String[]) test;    System.out.println(out[0]); // Prints 'hi'

But you actually have:

    String[] hi = { "hi" };    Object[] test = new Object[1]; // This is not a String[]    test[0] = hi[0];    String[] out = (String[]) test; // Cannot downcast, throws an exception.    System.out.println(out[0]);

You are getting back the immediate block above, which is why you're getting a casting error.

There's a few ways around it. If you want to go over your list, you could easily make an array out of them.

    Supplier<List<Integer>> supplier = () -> {         ArrayList<Integer> a = new ArrayList<Integer>();        a.add(5);        a.add(8);        return a;    };    Iterator<List<Integer>> i = Stream.generate(supplier).limit(3).iterator();    // This shows there are elements you can do stuff with.    while (i.hasNext()) {        List<Integer> list = i.next();        // You could add them to your list here.        System.out.println(list.size() + " elements, [0] = " + list.get(0));    }

If you are set on dealing with the function, you can do something like this:

    Supplier<List<Integer>> supplier = () -> {         ArrayList<Integer> a = new ArrayList<Integer>();        a.add(5);        a.add(8);        return a;    };    Object[] objArr = Stream.generate(supplier).limit(3).toArray();    for (Object o : objArr) {        ArrayList<Integer> arrList = (ArrayList<Integer>) o; // This is not safe to do, compiler can't know this is safe.        System.out.println(arrList.get(0));     }

According to the Stream Javadocs you can use the other toArray() method if you want to turn it into an array, but I've not explored this function yet so I don't want to discuss something I don't know.


Think the problem is that you are using toArray() without parameters that returns Object[]. Take a look at

public <T> T[] toArray(T[] a)