1

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?

Carlos Jaime C. De Leon
  • 2,476
  • 2
  • 37
  • 53

2 Answers2

3

Consider what you can do with a List<ViewableDTO>. You can add any object of a type implementing ViewableDTO. Do you really want this to compile?

List<PersonDTO> plist = getPersonDtoList();
List<ViewableDTO> vlist = plist;
vlist.add(new OtherDTO());

?

No - it's only safe to get things out of the list in that form, so you use something like this:

List<PersonDTO> plist = getPersonDtoList();
List<? extends ViewableDTO> vlist = plist;

See the Java Generics FAQ section on Wildcard Instantiations for more details.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

This will work

List<? extends ViewableDTO> vlist = plist;

Please take a look at What is PECS (Producer Extends Consumer Super)?

Community
  • 1
  • 1
denis.solonenko
  • 11,645
  • 2
  • 28
  • 23