Re: Generics
"kofa" <kovacs.it@gmail.com> wrote in message
news:1183112580.584626.138050@c77g2000hse.googlegroups.com...
Hello Oliver,
thanks for your reply. You are right, my code was all broken - don't
know why I did not just copy-paste the code I had written...
Sorry for being a nuisance: in theory I know what "? super X" means
("X or any supertype"), but haven't used it in practice. You left
EventMap.get() unimplemented, here's what I came up with:
===
private final Map<Class<? extends Event>, Set<EventListener<?>>>
myListenersByType = new HashMap<Class<? extends Event>,
Set<EventListener<?>>>();
public <T extends Event> Set<EventListener<? super T>> get(Class<?
extends T> key) {
Set<EventListener<? super T>> listeners = new HashSet<EventListener<?
super T>>();
for (Entry<Class<? extends Event>, Set<EventListener<?>>> entry :
myListenersByType.entrySet()) {
if (entry.getKey().isAssignableFrom(key)) {
listeners.add((EventListener<? super T>) entry.getValue());
}
}
return listeners;
}
===
Note that entry.getValue() returns an object of type
Set<EventListener<? super T>>, and you're casting that to EventListener<?
super T> which probably isn't what you want. Instead, you need to either
use addAll(), or iterate over the set and add each EventListener one by
one. Here's an example implementation of the later:
<code>
public <T extends Event> Set<EventListener<? super T>> get(
Class<? extends T> key) {
Set<EventListener<? super T>> listeners = new HashSet<EventListener<?
super T>>();
for (Entry<Class<? extends Event>, Set<EventListener<?>>> entry :
myListenersByType
.entrySet()) {
if (entry.getKey().isAssignableFrom(key)) {
for (EventListener<?> el : entry.getValue()) {
listeners.add((EventListener<? super T>) el);
}
}
}
return listeners;
}
</code>
- Oliver