Reputation: 833
I'm getting several compiler warnings about my use of generics in one class and could use some help. I have the following setup:
Map<EventType, List<? extends Listener>> map;
I have several different event types and for each one I want to keep a list of the corresponding listener type. Listener is an interface and there are several interfaces that extend it.
Later on I add a List to this map like:
List<StateListener> list = new LinkedList<StateListener>();
list.add(someStateListener);
map.put(Events.STATE, list);
And then I get warnings later on ...
List<StateListener> list = map.get(Events.STATE);
for unchecked conversion.
I read through some other posts but I didn't really see anything that helped. Thanks any comments
Upvotes: 1
Views: 916
Reputation: 359816
There's no guarantee that the List
returned by map.get()
is a List<StateListener>
. The compiler can only guarantees that, whatever map.get()
returns will be a List<? extends Listener>
.
So, either declare the Map
as a map of List<Listener>
, and deal with the limitation of not knowing which specific Listener
implementation an object that comes out of the map is:
Map<EventType, List<Listener>> map;
List<Listener> list = new LinkedList<Listener>();
list.add(someStateListener);
map.put(Events.STATE, list);
// later...
List<Listener> other = map.get(Events.STATE);
or be more specific in the declaration, and live with that limitation:
Map<EventType, List<StateListener>> map;
List<StateListener> list = new LinkedList<StateListener>();
list.add(someStateListener);
map.put(Events.STATE, list);
// later...
List<StateListener> other = map.get(Events.STATE);
Upvotes: 1
Reputation: 34527
You would have to use the class StateListener as the key for your map though.
Upvotes: 2
Reputation: 76908
There's no guarantee that the List
coming from map.get(Events.STATE)
is a List<StateListener>
since you declared the map with the value type of List<? extends Listener>
You need to cast it, or declare accordingly;
List<? extends Listener> list = map.get(Events.STATE);
Upvotes: 1