How to declare mixedList with generics for such snapshot without modifying the rest of the code?
List mixedList = new ArrayList();
if(flagA) {
ClassA a = new ClassA(); //comes from elsewhere
mixedList.add(a)
} else {
List<ClassB> bList = new ArrayList<ClassB>(); //comes from elsewhere
mixedList = bList; //error
}
I can do:
List<Object> mixedList = new ArrayList<Object>();
if(flagA) {
...
} else {
...
mixedList.addAll(bList);
}
but is there a way to avoid changing the code?
It’s not safe to assign
bList(List<ClassB>) tomixedList(List<Object>).The service from which you obtained
bListmight retain a reference to it; this service will assume its list contains onlyClassBinstances. If you were allowed to assign that list to aList<Object>reference, you could then add any type of object to the list without a warning. But when the service, thinking that every element in its list was aClassB, attempted to access the elements, aClassCastExceptionwould be raised.Creating a new
List<Object>, and adding elements to it withadd()oraddAll(), prevents this “type pollution”. You can safely modify this copy of the list, and let the source of the list keep its own copy “pure.”