简体   繁体   English

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

[英]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 . 您仍然可以将AttrKnotenGewKante对象添加到_graph


Alternatively, if you only want AttrKonten and GewKante objects, just declare it as: 另外,如果只需要AttrKontenGewKante对象,则将其声明为:

private Graph<AttrKnoten, GewKante> _graph;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么我将映射的类型不匹配作为路由参数? - Why do I get a type mismatch for a map as a routing parameter? 为什么会出现输入不匹配异常? - Why do I get Input Mismatch Exception? 将参数与PowerMockito模拟静态方法一起使用时,为什么参数类型不匹配? - Why do I get an argument type mismatch when I use arguments with PowerMockito mocked static method? 为什么在尝试在Java中反转字符串时会出现类型不匹配的问题? - Why do I get a type mismatch when trying to reverse a string in Java? 为什么会出现此错误“类型不匹配:无法从序列化转换为T”? - Why do I get this error “Type mismatch: cannot convert from Serializable to T”? 为什么Java在运行时检查类型与转换的不兼容性,并且在编译时键入不匹配转换? - Why in Java incompatibility of types to casting is checked at runtime and type mismatch to converting at compile time? 为什么我在Java中遇到这个编译错误? - Why do I get this compile error in Java? 为什么在 Java 中会出现此编译错误? - Why do I get this compile error in Java? 为什么在使用超类引用调用子类方法时出现编译时错误? - Why do I get a compile-time error when calling a subclass method using superclass reference? 为什么将“(F obj)”中的F替换为Factory时会引发类型不匹配错误。 编译时F是什么 - Why Type mismatch error is thrown up when F in “(F obj)” is replaced with Factory. What is F at compile time
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM