无法从ArrayList< Parcelable>转换到ArrayList< ClSprite> [英] Cannot cast from ArrayList<Parcelable> to ArrayList<ClSprite>
问题描述
在我编写的一段代码中,我有这一行:
In a piece of code I've written, I have this line:
AllSprites = (ArrayList<ClSprite>) savedInstanceState.getParcelableArrayList("AllSprites");
我收到来自 ArrayList< Parcelable>的无效演员的错误;
到 ArrayList< ClSprite>
。为什么这不合法呢?
I'm getting an error about an invalid cast from an ArrayList<Parcelable>
to ArrayList<ClSprite>
. Why isn't this legal?
推荐答案
施放 ArrayList< Derived> <从根本上说是不安全的/ code>到
ArrayList< Base>
,反之亦然。这样做会在类型系统中打开一个漏洞,如果您尝试这样做,Java将在运行时抛出 ClassCastException
。
It is fundamentally unsafe to cast an ArrayList<Derived>
to an ArrayList<Base>
or vice-versa. Doing so opens up a hole in the type system, and Java will throw a ClassCastException
at runtime if you try this.
原因是我可以这样做:
ArrayList<Derived> derived = new ArrayList<Derived>();
ArrayList<Base> base = (ArrayList<Derived>) derived; // Not legal!
base.add(new Base()); // Just put a Base into the list, but it only holds Derived!
derived.get(0).doSomethingOnlyInDerived(); // Error! It's not really a Derived!
顺便说一下,这就是Java在数组之间的隐式转换被破坏的原因以及为什么 ArrayStoreException信息
。在所有情况下,此演员阵容都不安全。
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.
这篇关于无法从ArrayList< Parcelable>转换到ArrayList< ClSprite>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!