Sarkhan
Sarkhan

Reputation: 1291

convert collection to array by type

I tested this code:

Collection l = new ArrayList<Object>();

l.add(5);
l.add("test");
l.add(6);

Integer[] arr= l.toArray(new Integer[2]);

I tried to get only Integers from this collection and got this exception:

Exception in thread "main" java.lang.ArrayStoreException
    at java.lang.System.arraycopy(Native Method)
    at java.util.Arrays.copyOf(Arrays.java:2248)
    at java.util.ArrayList.toArray(ArrayList.java:389)
    at c.Main.main(Main.java:15)

May be there is an other way to filter but I need to understand the toArray(Object[] a) method. Why can't I filter by telling type and size of the array?

Upvotes: 1

Views: 124

Answers (3)

Mureinik
Mureinik

Reputation: 311188

toArray attempts to store the entire collection in the given array. If you want to filter it, you'll have to do so yourself. E.g.:

Integer[] arr = 
    l.stream().filter(x -> x instanceof Integer).toArray(Integer[]::new);

Upvotes: 4

nits.kk
nits.kk

Reputation: 5316

Please look at the java doc of the method. Each method works as per the contract it declares to the outside world (as per the signature or java doc).

<T> T[] toArray(T[] a); Clearly says in its java doc the below statement.

Throws:ArrayStoreException - if the runtime type of the specified array is not a supertype of the runtime type of every element in this collection.

In your case type of each of your element is not Integer.

Upvotes: 2

Amit
Amit

Reputation: 46323

Why i can't filter by telling type and size of the array?

Because that's not what toArray() does, and nowhere does it say it can be used as a filter.

Functions & API's have definitions for what they do (and sometimes how they do that). You can't expect a function to do what you want it to do if it's not designed to do that.

Upvotes: 4

Related Questions