How to convert ArrayList<String> to String[] array in Java?
Hello everyone! I'm new to Java and encountered a problem while working with collections. I need to pass a list of strings from ArrayList to a method that only accepts a regular String[] array.
I tried simple type casting, but the compiler throws a ClassCastException. Here's my code:
```java
ArrayList list = new ArrayList<>();
list.add("apple");
list.add("banana");
list.add("cherry");
// Trying to convert to array
String[] array = (String[]) list.toArray(); // Error!
```
The documentation says that the `toArray()` method returns Object[], not String[]. How do I correctly get a String array from ArrayList? I've heard there's a way to pass an empty array to the method, but I don't understand how it works.
Please tell me the correct way to do it.
No answers yet.
Log in to leave an answer