Can't convert a generics list of objects into a generics list ofinterfaces

J

Juergen Berchtel

In the following lines of code I get this compiler error (getUnits):
Type mismatch: cannot convert from ArrayList<TestGen.Unit> to
List<TestGen.UnitI>


public class TestGen {
public UnitI getUnit() {
return new Unit();
}

public List<UnitI> getUnits() {
return new ArrayList<Unit>();
}

public interface UnitI { }
public class Unit implements UnitI {
}
}


The conversation works well with one object in getUnit() but I can't
convert the generics list.

Thanks for any help
Juergen
 
J

John C. Bollinger

Juergen said:
In the following lines of code I get this compiler error (getUnits):
Type mismatch: cannot convert from ArrayList<TestGen.Unit> to
List<TestGen.UnitI>


public class TestGen {
public UnitI getUnit() {
return new Unit();
}

public List<UnitI> getUnits() {
return new ArrayList<Unit>();
}

public interface UnitI { }
public class Unit implements UnitI {
}
}


The conversation works well with one object in getUnit() but I can't
convert the generics list.

You probably want

public List<UnitI> getUnits() {
return new ArrayList<UnitI>();
}

ArrayList<Unit> is not a subtype of List<UnitI> because if you have some
other implementation of UnitI then it is incorrect to put an instance in
an ArrayList<Unit>. Alternatively, you could declare the method to
return a List<? extends UnitI>, but then you could never add anything to
the returned List (without a type safety warning) because the specific
Unit implementation used by the returned List would be unknown.
Alternatively, you could return List<Unit>; this narrows the allowed
types of the List elements, which may be what you need.

If you're not sure which of those is most appropriate, then you need to
go back and think some more about how the returned List is intended to
be used. One of the nice things about Generics is that they do
encourage you to think these things out.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,733
Messages
2,569,440
Members
44,829
Latest member
PIXThurman

Latest Threads

Top