java - Error while adding items to a list with a wildcard -
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); }
i'm trying make logging class has option log events. purpose used map links identifier list of events. want able put type of object in list, once type of list determined, next items added list have conform first type. example:
logwriter.logevent("date", "0:00:01"); logwriter.logevent("date", "0:00:02"); logwriter.logevent("date", "0:00:03"); string[] = {"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);
but compile error @ the
eventsmap.get(eventidentifier).add(event);
no suitable method found add(class<cap#1>) method collection.add(cap#2) not applicable (argument mismatch; class<cap#1> cannot converted cap#2) method list.add(cap#2) not applicable (argument mismatch; class<cap#1> cannot converted cap#2) cap#1,cap#2 fresh type-variables: cap#1 extends object capture of ? cap#2 extends object capture of ?
please explain why , how can fix this.
you have wildcard in declaration eventsmap
:
private static map<string, list<?>> eventsmap = new hashmap<>();
this means list
s stored values in map lists of anything. doesn't mean can stored in it. list of specific yet unknown type. list<object>
, list<integer>
, or list<foo>
. type safety reasons, compiler must disallow such call add
, because cannot tell if event
of correct type.
because event
appears class
, replace wildcard class<?>
:
private static map<string, list<class<?>>> eventsmap = new hashmap<>();
this way class
object representing class can inserted lists retrieved map.
Comments
Post a Comment