File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

ArrayList Conversion

 
Mark Reyes
Ranch Hand
Posts: 426
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Everyone,

I know that this question was posted several times but I can't find the answer to my query. I need to convert an arraylist to String array.



But I keep on having error java.lang.ClassCastException

I thought calling myArrayList.toArray() would return an Object[] array so I did cast it to (String[]) but I still get the error.

I did try to experiment and adjusted my code below and it works fine but with Object as my data type.



Also, I found a resource on the Search on javaranch and found a good example on arraylist to array conversion and it works well.



But I'm just wondering why my first code does not work whereas I declare my arrayList as String. I know I'm missing something here. Please help.
 
John William
Greenhorn
Posts: 5
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I thought Array don't convert with the method below:

Sting[] anArray = (String[])myArrayList.toArray();

In my Opinion,once you declared an Array,it will not convert data type.

In Addition,your code may write in this way:


Good Luck
 
Rob Spoor
Sheriff
Pie
Posts: 20393
46
Chrome Eclipse IDE Java Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by mark reyes:

But I'm just wondering why my first code does not work whereas I declare my arrayList as String. I know I'm missing something here. Please help.

Look at the API.

toArray() returns an Object[]. This is created as an Object[], not a String[]. Therefore, you cannot cast it to String[].

toArray(T[]) returns a T[] (for whatever T you want). So if you want toArray to return a String[], you need this version and pass it any String[] array.
Performance dictates that you should use either an array that will be large enough for all elements (so using the collection size is good) or a cached version of an empty array. This is because if the passed array is not large enough a new array will be created. Imagine creating an array for the sake of getting the right type of array, then having another array be created within toArray. Either skip the creation of the passed array (cached empty array) or the creation within toArray (by passing an array that is large enough).
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic