In a piece of code I’ve written, I have this line:
AllSprites = (ArrayList<ClSprite>) savedInstanceState.getParcelableArrayList("AllSprites");
I’m getting an error about an invalid cast from an ArrayList<Parcelable> to ArrayList<ClSprite>. Why isn’t this legal?
It is fundamentally unsafe to cast an
ArrayList<Derived>to anArrayList<Base>or vice-versa. Doing so opens up a hole in the type system, and Java will throw aClassCastExceptionat runtime if you try this.The reason is that I could do something like this:
This is the reason, by the way, that Java’s implicit conversions between arrays are broken and why there’s
ArrayStoreException. This cast isn’t safe under all cases.