(amapList is an ArrayList containing one or more AttributeMappingRuleTO)
I'd think that, since the objects contained in amapList is of the type I'm casting to, the first code should work. Why does it not? [ December 05, 2005: Message edited by: �dne Brunborg ]
This is definitely a frustrating one, and one I get annoyed with myself at times.
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 (AttributeMappingRuleTO[]), will not work.
Keep in mind, there are two object types being defined here, the type for the objects in the array (which can vary), and the type of object of the array itself. Without clear direction from the developer as to what the array's object type is, the runtime system has no choice but to declare it as Object[] which cannot be cast down even though it may contain elements that all belong to the same type.
The way I think of this is: The toArray() method can't see your cast so you have to tell it what kind of array to make. It returns the array you pass in if it's big enough or makes a new one of the same type if it's not big enough.
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Originally posted by Stan James: The way I think of this is: The toArray() method can't see your cast so you have to tell it what kind of array to make. It returns the array you pass in if it's big enough or makes a new one of the same type if it's not big enough.
Doesn't "MyClass[] myArray = (MyClass[]) list.toArray(new MyClass[size]);" seem excessive though? I've written the code to do this multiple times and every time I think to myself, "wow its really irritating to be listing the class 3 times".