Showing posts with label toArray class cast exception. Show all posts
Showing posts with label toArray class cast exception. Show all posts

Wednesday, August 10, 2011

toArray() class cast exception

List<Record> recordsList = new ArrayList<Record>(2);
...
Record[] records = (Record[]) recordsList.toArray() ; //incorrect
Record[] records = (Record[]) recordsList.toArray(new Record[2]); //correct

Why Class cast exception ?
Recall that a Collection can contain objects of vastly different types. There's no 'general' rule that objects in a Collection must all be of the exact same type. So when toArray() is being calling, it allocates a typed array Object[] which has no sub-classes defined. Therefore casting it to any form such as (Record[]), will not work.

toArray() method can't see your cast so you have to tell it what kind of array to make.