Given:
interface ViewableDTO {//methods here}
class PersonDTO implements ViewableDTO {//implementation here}
This works fine:
PersonDTO p = new PersonDTO();
ViewableDTO v = p; //works
How come this doesn’t work:
List<PersonDTO> plist = getPersonDtoList();
List<ViewableDTO> vlist = plist; //compilation error
List<ViewableDTO> vlist = (List<ViewableDTO>)plist; //compilation error
My solution here is to do this:
List<ViewableDTO> vlist = new ArrayList<ViewableDTO>();
vlist.addAll(plist);
My question is, is this the only / best way to do it?
Consider what you can do with a
List<ViewableDTO>. You can add any object of a type implementingViewableDTO. Do you really want this to compile??
No – it’s only safe to get things out of the list in that form, so you use something like this:
See the Java Generics FAQ section on Wildcard Instantiations for more details.