Java 类型转换问题

发布于 2024-11-09 19:49:34 字数 775 浏览 3 评论 0原文

可能的重复:
如何转换矢量到 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?
Is List<Dog> a subclass of List<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 like
A 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

哆兒滾 2024-11-16 19:49:34

java 泛型不支持协方差,因此 Vector 不会扩展 Vector

java generics don't support co-variance, so Vector<B> does NOT extend Vector<A>

东风软 2024-11-16 19:49:34

可以这样想;

如果 C 也扩展了 B,那么您可以将 C 放入 Vector 中。

现在,如果您可以将其转换为 Vector 并执行 get,您将获得 C 的实例!

这没有多大意义,因此编译器不允许这样做。正如 @amit 所说,协方差就是这个的名称。

请参阅此帖子

Think of it like this;

If C also extends B then you could put C into Vector<B>.

Now if you could cast it to a Vector<A> and you did a get you would get an instance of C!

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

不…忘初心 2024-11-16 19:49:34

变量的类型必须与传递给实际对象类型的类型匹配。

当涉及到泛型类型的多态性时,java不允许您这样做:

class A { } 
class B extends A { } 
List<A> myList = new ArrayList<B>();

这是因为在编译时,编译器摆脱了泛型类型(通过称为类型擦除的东西)并且做了它在前java中所做的事情5 代码。这很令人困惑,因为它与数组的行为不同。使用数组,您可以这样做:

A[] myArr = new B[10];

但泛型的情况并非如此。同样,当涉及到泛型时,变量的类型必须与传递给实际对象类型的类型相匹配。

希望有帮助!

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:

class A { } 
class B extends A { } 
List<A> myList = new ArrayList<B>();

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:

A[] myArr = new B[10];

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!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文