0 votes
1 view
in Java by (2.6k points)

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

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

If I define as follows:

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

It operates. Is there something that I'm avoiding?

1 Answer

0 votes
by (32.7k points)

The reason behind it is that stock_list.toArray() is creating an Object[] rather than a String[] and hence the typecast is missing.

Try this syntax instead:

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

...