1

From the Java Docs of ArrayStoreException

Thrown to indicate that an attempt has been made to store the wrong type of object into an array of objects.

To avoid this exception i used generics.But when i ran the following Test program:

public class Test {
    public static void main(String[] args) {
        Collection<Number> nums = new ArrayList<Number>();
        nums.add(new Integer(1));
        nums.add(new Long(-1));
        Integer[] ints = nums.toArray(new Integer[nums.size()]);

        for (Integer integer : ints) {
            System.out.println(integer);
        }
    }
}

I am getting ArrayStoreException as below - Which i am not expecting.

Exception in thread "main" java.lang.ArrayStoreException
    at java.lang.System.arraycopy(Native Method)
    at java.util.ArrayList.toArray(ArrayList.java:408)

Can some one help me understand why is this exception thrown even if my list is of generic type.

T-Bag
  • 10,916
  • 3
  • 54
  • 118

1 Answers1

4

Your ArrayList contains a Long. A Long cannot be stored in an Integer array, since Integer is not a super type of Long.

The following will work:

Number[] ints = nums.toArray(new Number[nums.size()]);

for (Number integer : ints) {
    System.out.println(integer);
}

This is clearly stated in the Javadoc of toArray:

Throws:

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

Eran
  • 387,369
  • 54
  • 702
  • 768