[英]Why do I get a type mismatch during compile time
I'm declaring a graph (using JUNG's Graph interface) as a class variable like this: 我正在声明一个图(使用JUNG的Graph接口)作为这样的类变量:
private Graph<Knoten, Kante> _graph;
I try to initialize it like this: 我尝试像这样初始化它:
_graph = new DirectedSparseGraph<AttrKnoten, GewKante>();
AttrKnoten extends Knoten and GewKante extends Kante (they are just marker interfaces at the moment). AttrKnoten扩展了Knoten,而GewKante扩展了Kante(目前它们只是标记界面)。 I get the following error message during compile time:
我在编译时收到以下错误消息:
"Type mismatch: cannot convert from DirectedSpareGraph<AttrKnoten, GewKante> to Graph<Knoten, Kante>"
Why is that? 这是为什么? Is there any other way to handle this, but leaving out the parameters during declaration?
还有其他方法可以解决此问题,但在声明过程中会遗漏参数吗?
You can't do that with generics. 使用泛型无法做到这一点。
A simpler example: 一个简单的例子:
List<CharSequence> list = new ArrayList<String>();
This doesn't work, even though String
implements CharSequence
. 即使
String
实现CharSequence
,这也不起作用。
The easiest solution is to just do: 最简单的解决方案是执行以下操作:
_graph = new DirectedSparseGraph<Knoten, Kante>();
You can still add AttrKnoten
and GewKante
objects to _graph
. 您仍然可以将
AttrKnoten
和GewKante
对象添加到_graph
。
Alternatively, if you only want AttrKonten
and GewKante
objects, just declare it as: 另外,如果只需要
AttrKonten
和GewKante
对象,则将其声明为:
private Graph<AttrKnoten, GewKante> _graph;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.