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.

How to return a generic array

Thread view: 
dgront - 08 May 2007 17:59 GMT
Hello,

I found that I can create a generic array and fill it with some data,
but I cannot return it. What is going on?
The example below throws ClassCastException:

public class Test {

 public <T> T[] test(T val,int n) {
   T[] array = (T[]) new Object[n];
   for(int i=0;i<n;i++) {
     array[i] = val;
     System.out.println("inserted "+array[i]);
   }

   return array;
 }

 public static void main(String[] args) {

   Test tt = new Test();
   String[] ss = tt.test("empty",3);
   for(String s: ss) System.err.println(s);
 }
}
Tom Hawtin - 08 May 2007 18:31 GMT
> I found that I can create a generic array and fill it with some data,
> but I cannot return it. What is going on?

You're not creating a generic array. You are creating a non-generic
array and then incorrectly casting it.

Given a Class<T> (T will not be generic itself), you can create an array
of T[] using java.lang.reflect.Array.newInstance.

Given an existing T[] you can get Class<T[]> through Object.getClass.
Form Class<T[]> you can get a Class<?> that, although having a wildcard,
is the same instance as T.class. You can create an array with the
correct runtime type from this, and then do an unsafe cast to correct
the compile-time type.

Better still, avoid using arrays of references and stick with the likes
of List<T>.

Tom Hawtin


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.