Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / May 2005

Tip: Looking for answers? Try searching our database.

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

Thread view: 
Juergen Berchtel - 20 May 2005 13:34 GMT
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
John C. Bollinger - 20 May 2005 15:07 GMT
> In the following lines of code I get this compiler error (getUnits):
> Type mismatch: cannot convert from ArrayList<TestGen.Unit> to
[quoted text clipped - 16 lines]
> 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.

Signature

John Bollinger
jobollin@indiana.edu



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.