Converting List to Array in Java: How to Do It Correctly?
Hello everyone! I'm just starting to learn Java and ran into this problem. I have an ArrayList with strings, and I need to convert it to a regular String[] array to pass to some old method that only accepts arrays.
I wrote this code:
```java
List list = new ArrayList<>();
list.add("Java");
list.add("Python");
list.add("C++");
// Attempt 1: just assign
String[] array = list; // Compilation error: incompatible types
// Attempt 2: use toArray()
String[] array2 = list.toArray(); // Error: Object[] cannot be converted to String[]
```
The first option doesn't work because List is an interface, not an array. The second option returns Object[], not String[], even though the list only contains strings. I read that you can use
No answers yet.
Log in to leave an answer
Blogs
Testing in Java: unit, integration, e2e — a complete guide