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 2007

Tip: Looking for answers? Try searching our database.

returning a generic array

Thread view: 
ndac - 21 Mar 2007 20:35 GMT
Hello,

assume I have the following:

public interface X<E> {
       ...
       E[] toArray();
}
public class XImp<E> {
       E[] toArray(){
               E[] a = (E[])new Object[N];
               ...
               return a;
       }
}

using this like this gives me a bad cast exception?
X<String> x = new X<String>();
...
String[] a = x.toArray();
(or String[] a = (String[])x.toArray();)

what am I doing wrong here?

Regards
Lew - 24 Mar 2007 04:46 GMT
> Hello,
>
[quoted text clipped - 19 lines]
>
> what am I doing wrong here?

Arrays and generics don't play well together.

-- Lew
Alex Gout - 24 Mar 2007 23:08 GMT
ndac schreef:
> Hello,
>
[quoted text clipped - 21 lines]
>
> Regards

You cannot just cast an object array to another type array. It's not
just because you use generics, it's just the way arrays work.
jupiter - 28 May 2007 18:54 GMT
> Hello,
>
[quoted text clipped - 19 lines]
>
> what am I doing wrong here?

Don't forget: .toArray() must return Object[].  It would be nice to
be able to cast from Object[] to String[] but you can't.

You can cast the items though after storing them in Object[]
though.

Object[] obj = x.toArray();
String[] str = null;
str[0] = (String)obj[0];

Of course the cast could be wrong at runtime.  You have to make
sure that all the objects in obj can be represented by String.

Seems to me that it would be nice to have .toArray() return the
correct type someday.  But even if the cast you tried to do would
work, you'd still have the same problem at runtime if one of the
objects was not capable of being represented by String.  I don't
think it's a trivial fix.


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.