本文介绍了无法投射通用集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天我遇到了一个有趣的问题。考虑以下代码:

  public static class Parent {} 
public static class Child extends Parent {}

设置< Child> childs = new HashSet();
Set< Parent>父母=(设置<父>)孩子; //错误:不可兑换的类型

父亲=(父)new Child(); //作品?!

为什么不能像这样工作?我希望隐式转换不会因泛型的各种规则而起作用,但为什么不能进行显式转换呢?

解决方案

转换不起作用,因为 Java泛型不是协变

如果编译器允许:

  List< ;儿童> children = new ArrayList(); 
列表< Parent>父母=(列表<父>)子女;

那么在这种情况下会发生什么情况?

  parents.add(new Parent()); 
Child c = children.get(0);

最后一行会尝试分配小孩—但是 不是小孩 c $!

所有小孩都是父母(因为 Child extends Parent ),但所有父母都不是小孩


I'm ran into an interesting issue today. Consider the following code

public static class Parent {}
public static class Child extends Parent {}

Set<Child> childs = new HashSet();
Set<Parent> parents = (Set<Parent>)childs; //Error: inconvertible types

Parent parent = (Parent)new Child(); //works?!

Why wouldn't a cast like that work? I would expect that an implicit cast wouldn't work due to the various rules of generics, but why can't an explicit cast work?

解决方案

The cast doesn't work because Java generics are not covariant.

If the compiler allowed this:

List<Child> children = new ArrayList();
List<Parent> parents = (List<Parent>)children;

then what would happen in this case?

parents.add(new Parent());
Child c = children.get(0);

The last line would attempt to assign Parent to a Child — but a Parent is not a Child!

All Child are Parent (since Child extends Parent) but all Parent are not Child.

这篇关于无法投射通用集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 06:52