【发布时间】:2015-04-14 19:58:31
【问题描述】:
private static Map<String, List<?>> eventsMap = new HashMap<>();
public static void logEvent(String eventIdentifier, Class<?> event) {
if (!eventsMap.containsKey(eventIdentifier)) {
eventsMap.put(eventIdentifier, new ArrayList<>());
}
eventsMap.get(eventIdentifier).add(event);
}
我正在尝试创建一个可以记录事件的日志类。为此,我使用了一个将标识符链接到事件列表的 Map。我希望能够将任何类型的对象放入列表中,但是一旦确定了列表的类型,添加到列表中的所有下一个项目都必须符合第一种类型。例如:
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);
但是我得到一个编译错误
eventsMap.get(eventIdentifier).add(event);
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 ?
请解释为什么以及如何解决这个问题。
【问题讨论】:
标签: java list generics compiler-errors wildcard