开发者

Unchecked conversion compiler warning java

开发者 https://www.devze.com 2023-04-12 21:43 出处:网络
I\'m getting several compiler warnings about my use of generics in one class and could use some help. I have the following setup:

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开发者_StackOverflow 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


Effective Java for the Win: http://books.google.com/books?id=ka2VUBqHiWkC&pg=PA142&lpg=PA142&dq=consider+type+safe+heterogeneous+containers&source=bl&ots=yYDnLlu3P2&sig=Yp3JqYaFwrqHVxAP0OKVVgLAg3Q&hl=en&ei=pdiUTs-1FYTw0gGbqoiJCA&sa=X&oi=book_result&ct=result&resnum=2&ved=0CCAQ6AEwAQ#v=onepage&q&f=false

You would have to use the class StateListener as the key for your map though.


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);


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号