Home >Java >javaTutorial >How to Safely Convert an ArrayList to a String[] Array in Java?
Convert ArrayList
To convert an ArrayList
// Define your ArrayList of strings List<String> stockList = new ArrayList<>(); stockList.add("stock1"); stockList.add("stock2"); // Create a new String array with the same size as the ArrayList int arraySize = stockList.size(); String[] stockArr = new String[arraySize]; // Copy the ArrayList elements into the String array using toArray() stockList.toArray(stockArr); // Print the contents of the String array for (String s : stockArr) { System.out.println(s); }
This solution involves creating a new String array of the same size as the ArrayList and then using the toArray() method to copy the ArrayList elements into the new array. This approach ensures that the conversion is done correctly without any exceptions.
The above is the detailed content of How to Safely Convert an ArrayList to a String[] Array in Java?. For more information, please follow other related articles on the PHP Chinese website!