Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am trying to convert Array list to String array but getting an exception. Can somebody please help me.

Size of ArrayList: 1
Size of String Array: 2

I am using the following code:

String[] StringArray ={};
StringArray = ArrayList.toArray(new String[ArrayList.size()]);

So, the length of StringArray now is 1. But it should be 2. My problem is how can i convert arraylist to StringArray if String Array size is more than the ArrayList.

How can i do that? Please guys help me.

share|improve this question
1  
That would not compile: toArray is not a static method of the ArrayList class. Is that your real code? –  assylias May 22 '13 at 12:00
1  
Why it should be 2 ? –  rockskull May 22 '13 at 12:01
3  
possible duplicate of convert String arraylist to string array in java? –  ZouZou May 22 '13 at 12:01
    
I think, that there is no statis call... he just named variables ArrayList and StringArray –  Martin Perry May 22 '13 at 12:02
    
no, its not a duplicate of the question linked. My problem is how can i convert arraylist to StringArray if String Array size is more than the ArrayList. Guys please help me. –  Avadhani Y May 22 '13 at 12:04

3 Answers 3

up vote 4 down vote accepted

If you want to convert ArrayList to a bigger String array, use toArray() and pass the array you want to fill as parameter. If the array size is more than needed, the rest of the elements will be null. If the array is smaller - a new array will be returned with size as list.size.

All taken from javadoc

ArrayList<String> list  = new ArrayList<>();
list.add("abc");

String[] StringArray = new String[2];
StringArray = list.toArray(StringArray);

In that case, even though the list size is 1, StringArray is of size 2, adding null values at the end of the array.

share|improve this answer
    
Thanks buddy, This is I want.... +1ed, accepted –  Avadhani Y May 22 '13 at 12:17
    
Glad I could help :) –  BobTheBuilder May 22 '13 at 12:18
 String[] arr = new String[list.size()];
 arr = list.toArray(arr);
share|improve this answer

Try to do it like in this tutorial: http://viralpatel.net/blogs/convert-arraylist-to-arrays-in-java/

The size of array defined before .toArray method has no effect on result. After calling .toArray, old array is destroyed by JVM.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.