Java 使用通配符将项目添加到列表时出错
但是我得到了一个编译错误在Java 使用通配符将项目添加到列表时出错,java,list,generics,compiler-errors,wildcard,Java,List,Generics,Compiler Errors,Wildcard,但是我得到了一个编译错误在 eventsMap.get(eventIdentifier).add(event) 找不到适合添加(类)的方法 方法集合。添加(第2章)不适用 (参数不匹配;类无法转换为CAP#2) 方法列表。添加(第2章)不适用 (参数不匹配;类无法转换为CAP#2) 其中,CAP#1、CAP#2是新类型变量: CAP#1将对象从捕获扩展到? CAP#2将对象从捕获扩展到? 请解释为什么以及如何解决此问题。您在事件的声明中有一个通配符map: no suitable method
eventsMap.get(eventIdentifier).add(event)代码>
找不到适合添加(类)的方法
方法集合。添加(第2章)不适用
(参数不匹配;类无法转换为CAP#2)
方法列表。添加(第2章)不适用
(参数不匹配;类无法转换为CAP#2)
其中,CAP#1、CAP#2是新类型变量:
CAP#1将对象从捕获扩展到?
CAP#2将对象从捕获扩展到?
请解释为什么以及如何解决此问题。您在事件的声明中有一个通配符map
:
no suitable method found for add(Class<CAP#1>)
method Collection.add(CAP#2) is not applicable
(argument mismatch; Class<CAP#1> cannot be converted to CAP#2)
method List.add(CAP#2) is not applicable
(argument mismatch; Class<CAP#1> cannot be converted to CAP#2)
where CAP#1,CAP#2 are fresh type-variables:
CAP#1 extends Object from capture of ?
CAP#2 extends Object from capture of ?
通过这种方式,可以将表示任何类的Class
对象插入到从地图检索的列表中。另请参阅,谢谢您的快速回复!我不想在列表中插入'Class'对象,我试图找到将'event'放入列表的方法“事件”通常是“列表”或“字符串”对象。至少现在我知道“类事件”作为方法参数不起作用,谢谢!您将事件
的类型指定为类
。无论如何,如果事件
是Foo
,则映射的类型应为映射
。
LogWriter.logEvent("date", "0:00:01");
LogWriter.logEvent("date", "0:00:02");
LogWriter.logEvent("date", "0:00:03");
String[] a = {"street", "zipcode", "housenumber", "city"};
String[] b = {"street", "zipcode", "housenumber", "city"};
String[] c = {"street", "zipcode", "housenumber", "city"};
LogWriter.logEvent("address", a);
LogWriter.logEvent("address", b);
LogWriter.logEvent("address", c);
no suitable method found for add(Class<CAP#1>)
method Collection.add(CAP#2) is not applicable
(argument mismatch; Class<CAP#1> cannot be converted to CAP#2)
method List.add(CAP#2) is not applicable
(argument mismatch; Class<CAP#1> cannot be converted to CAP#2)
where CAP#1,CAP#2 are fresh type-variables:
CAP#1 extends Object from capture of ?
CAP#2 extends Object from capture of ?
private static Map<String, List<?>> eventsMap = new HashMap<>();
private static Map<String, List<Class<?>>> eventsMap = new HashMap<>();