-1

Possible Duplicate:
Convert ArrayList<String> to String []

How do I convert an ArrayList to a String[]?

For example, my ArrayList is

arrlist=[audio,video,song,tech]

I want to convert it to a String[] like this:

String[] data;

data={ "audio","video","song","tech"};

My issue is that ArrayList data can be changed dynamically, but I would like a return format in a finite sized array.

Community
  • 1
  • 1
EESHA
  • 39
  • 2
  • 6

2 Answers2

12

You can use toArray(T[]):

ArrayList<?> foo;
String[] data = foo.toArray(new String[foo.size()]);

You don't have to pass a non-zero length array to this function, but if you do and it's big enough, toArray will simply use it, if you don't then toArray will make a second allocation. This isn't so much a fine optimization point; rather, it's the standard convention.

Also note that the String[] is not immutable, it's only fixed size. Both the ArrayList and String[] will allow your data to "change"; if you want an immutable list (a list that cannot be edited and which contents cannot be replaced), you can find one in Google Guava, or implement your own trivially.

Mark Elliot
  • 75,278
  • 22
  • 140
  • 160
2

from

Convert ArrayList<String> to String[] array

 ArrayList<String> stock_list = new ArrayList<String>();
    stock_list.add("stock1");
    stock_list.add("stock2");
    String[] stockArr = new String[stock_list.size()];
    stockArr = stock_list.toArray(stockArr);
    for(String s : stockArr)
        System.out.println(s);

from http://viralpatel.net/blogs/2009/06/convert-arraylist-to-arrays-in-java.html

Community
  • 1
  • 1
Dheeresh Singh
  • 15,643
  • 3
  • 38
  • 36