Skip to Main Content

Java APIs

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Solution for toArray() problems

843793Nov 30 2004 — edited May 24 2007
Hey everyone,

My familiarity with using the "generics" jargon is very weak, so I will just explain in code. I saw that a few people were having trouble with situations like the following:
  ArrayList<String> al = new ArrayList<String>();
  // add some data
  String[] s = al.toArray();
This will generate a compile time error claiming incompatible types, which is always frustrating. You created the ArrayList to support Strings, so why can't it return an array of Strings? Definitely frustrating.

A workaround, although maybe not the best or most efficient, is the following:
  ArrayList<String> al = new ArrayList<String>();
  // add some data
  String[] s = al.toArray(new String[al.size()]);
If you don't provide the array size to the constructor, it fails.

Anyway, I hope this helps somebody.

-Steven
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jun 21 2007
Added on Nov 30 2004
12 comments
2,026 views