I stumbled upon this interesting cast/generics problem today:
public class A {
Map<Class<? extends B>, List<Set<B>>> mapListSet = new HashMap<>();
Map<Class<? extends B>, Set<B>> mapSet = new HashMap<>();
public <T extends B> List<Set<T>> foo(Class<T> clazz) {
List<Set<T>> listSet = (List<Set<T>>) mapListSet.get(clazz);
return listSet;
}
public <T extends B> Set<T> bar(Class<T> clazz) {
Set<T> set = (Set<T>) mapSet.get(clazz);
return set;
}
}
class B {
}
I can compile the method "bar" with only one warning from the IDE, whereas the IDE completely refuses to compile method "foo". This is a simplified example taken from my recently written code, does anyone know if I can make it more elegant rather than just doing this?
public <T extends B> List<Set<T>> foo(Class<T> clazz) {
List<Set<T>> listSet = (List) mapListSet.get(clazz);
return listSet;
}
Any help is hugely appreciated, I have a feeling this code smells really bad and I would love to improve on it.
> to List
> causes compilation error, but casting List to List causes warning?](https://stackoverflow.com/q/74923840)