Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
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 (46k 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);

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Aug 29, 2019 in Java by Ritik (3.5k points)
0 votes
1 answer
asked Jul 27, 2019 in Java by Ritik (3.5k points)
0 votes
1 answer

Browse Categories

...