Home >Java >javaTutorial >How to Properly Convert an ArrayList to a String[] Array in Java?

How to Properly Convert an ArrayList to a String[] Array in Java?

Linda Hamilton
Linda HamiltonOriginal
2024-12-11 08:25:10877browse

How to Properly Convert an ArrayList to a String[] Array in Java?

Converting ArrayList to String[] Arrays in Java

Attempting to convert an ArrayList to a String[] array using the toArray() method may not always work as expected. The original question highlights this issue.

To successfully perform this conversion, the correct approach is to create a new String[] array of the same size as the ArrayList. Then, use the toArray(stockArr) method, where stockArr is the newly created array, to populate it with the values from the ArrayList.

Code Example:

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

Output:

stock1
stock2

By following this approach, you can successfully convert an ArrayList to a String[] array and access its elements as needed.

The above is the detailed content of How to Properly Convert an ArrayList to a String[] Array in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn