Convert ArrayList<String> to String[] array

locoboy picture locoboy · Mar 21, 2011 · Viewed 1.5M times · Source

I'm working in the android environment and have tried the following code, but it doesn't seem to be working.

String [] stockArr = (String[]) stock_list.toArray();

If I define as follows:

String [] stockArr = {"hello", "world"};

it works. Is there something that I'm missing?

Answer

Prince John Wesley picture Prince John Wesley · Mar 21, 2011

Use like this.

List<String> stockList = new ArrayList<String>();
stockList.add("stock1");
stockList.add("stock2");

String[] stockArr = new String[stockList.size()];
stockArr = stockList.toArray(stockArr);

for(String s : stockArr)
    System.out.println(s);