Java 类型转换问题
可能的重复:
如何转换矢量到 Vector 在Java中?
是List<Dog& gt;
List
的子类?为什么 Java 的泛型不是隐式多态的?
我在 java 类型转换方面遇到了逻辑问题。 我有一个类 A ,它扩展了类 B ,因此我可以有这样的声明 A a = new B();
但为什么我收到 Vector 的编译器错误? va = new Vector();
或 Vector
; va = (Vector)new Vector();
Possible Duplicates:
How to Cast a Vector<ObjectA> to Vector<ObjectB> in Java?
IsList<Dog>
a subclass ofList<Animal>
? Why aren't Java's generics implicitly polymorphic?
I've a logical problem with the java type casting.
I have a class A which extends class B and therefore I can have a statement likeA a = new B();
but why I get a compiler error for Vector<A> va = new Vector<B>();
or Vector<A> va = (Vector<A>)new Vector<B>();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
java 泛型不支持协方差,因此
Vector
不会不扩展Vector
java generics don't support co-variance, so
Vector<B>
does NOT extendVector<A>
可以这样想;
如果
C
也扩展了B
,那么您可以将C
放入Vector
中。现在,如果您可以将其转换为
Vector
并执行get
,您将获得C
的实例!这没有多大意义,因此编译器不允许这样做。正如 @amit 所说,协方差就是这个的名称。
请参阅此帖子
Think of it like this;
If
C
also extendsB
then you could putC
intoVector<B>
.Now if you could cast it to a
Vector<A>
and you did aget
you would get an instance ofC
!That wouldn't make much sense so the compiler doesn't allow it. As @amit says Co-variance is the name for this.
See this posting
变量的类型必须与传递给实际对象类型的类型匹配。
当涉及到泛型类型的多态性时,java不允许您这样做:
这是因为在编译时,编译器摆脱了泛型类型(通过称为类型擦除的东西)并且做了它在前java中所做的事情5 代码。这很令人困惑,因为它与数组的行为不同。使用数组,您可以这样做:
但泛型的情况并非如此。同样,当涉及到泛型时,变量的类型必须与传递给实际对象类型的类型相匹配。
希望有帮助!
The type of the variable must match the type you pass to the actual object type.
When it comes to polymorphism with regards to generic type, java does not allow you to as follows:
This is because on compilation, the compiler gets rid of generic typing (through something called type erasure) and does was it used to do in pre java 5 code. This is confusing because it is not the same behavior with arrays. With arrays you can do:
But such is not the case with generics. Again, when it comes to generics the type of the variable must match the type you pass to the actual object type.
Hope that helps!