HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavaCritical

Convert ArrayList<String> to String[] array

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
arraystringconvertarraylist

Problem

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?

Solution

Use like this.

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

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

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

Code Snippets

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);

Context

Stack Overflow Q#5374311, score: 1833

Revisions (0)

No revisions yet.