|
|
|
|
|
by rocqua
765 days ago
|
|
At least back in the day (might be fixed now) with type covariant mutable arrays. That is array of cat is a subtype of array of animal. And a function Foo taking an array of animals and appending a dog is legal. Because array of cat is a subtype of array of animal, you can pass an array of cats to foo and append a dog. I believe this causes a runtime type exception, in a type-checked language without using any dangerous casts. I kind of assume modern java has addressed this somehow, I would love to hear how. |
|
I'm not that familiar with Java, but in C#, the only ways to avoid the penalty are either making the class of the array type sealed (so the runtime knows that you can't put any subtype into it) or using a construct like this if you work with someone else's type which you can't make sealed:
(this doesn't bounds check either, and hard-crashes on an empty array so you need to guard it appropriately)