I created the following Test class:
public class GenericTest {
public static class A implements Serializable {
}
public static class B implements Serializable {
}
public static void main(String[] args) {
// Error: Type mismatch: cannot convert from List<capture#1-of ? extends Serializable> to List<GenericTest.A>
//List<A> aList = getInfo().get("A");
//List<B> BList = getInfo().get("B");
// Warning: Type safety: Unchecked cast from List<capture#1-of ? extends Serializable> to List<GenericTest.A>
List<A> aList = (List<A>)getInfo().get("A");
List<B> BList = (List<B>)getInfo().get("B");
}
public static Map<String, List<? extends Serializable>> getInfo() {
Map<String, List<? extends Serializable>> infoMap = new HashMap<String, List<? extends Serializable>>();
List<A> aList = new ArrayList<A>();
List<B> bList = new ArrayList<B>();
try {
aList.add(new A());
infoMap.put("A", aList);
bList.add(new B());
infoMap.put("B", bList);
}
catch(Exception e) {
e.printStackTrace();
}
return infoMap;
}
}
Is there a better way to go about this to avoid casting and suppressing the unchecked warning? I have been told using casting almost defeats the purpose of using Generics in the first place. Is there a problem with this, or a “safer” way to go about doing it?
No, there is no way to help this situation. You have a single map with two kinds of values (this is called a heterogeneous map) and the type system cannot express that. You must downcast without type safety. Either that, or completely redesign to keep these two kinds of objects in two separate structures.