转换 ArrayList<String>到 String[] 数组

2022-01-31 00:00:00 arrays arraylist java

我是在android环境下工作,试过下面的代码,但是好像不行.

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

如果我定义如下:

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

它有效.有什么我遗漏的吗?

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

推荐答案

这样使用.

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

相关文章