为什么在编译时会出现类型不匹配

Why do I get a type mismatch during compile time

我将一个图(使用 JUNG 的 Graph 接口)声明为一个 class 变量,如下所示:

private Graph<Knoten, Kante> _graph;

我尝试这样初始化它:

_graph = new DirectedSparseGraph<AttrKnoten, GewKante>();

AttrKnoten 扩展了 Knoten,GewKante 扩展了 Kante(目前它们只是标记接口)。我在编译期间收到以下错误消息:

"Type mismatch: cannot convert from DirectedSpareGraph<AttrKnoten, GewKante> to Graph<Knoten, Kante>"

这是为什么?有没有其他方法可以处理这个问题,但在声明期间省略参数?

你不能用泛型做到这一点。

一个更简单的例子:

List<CharSequence> list = new ArrayList<String>();

这不起作用,即使 String 实现了 CharSequence


最简单的解决方案就是:

_graph = new DirectedSparseGraph<Knoten, Kante>();

您仍然可以将 AttrKnotenGewKante 个对象添加到 _graph


或者,如果您只需要 AttrKontenGewKante 对象,只需将其声明为:

private Graph<AttrKnoten, GewKante> _graph;