Converting ArrayList<String> to String[] in Java: how to do it correctly?
Hi everyone! I'm new to Java and ran into this problem. I have an ArrayList<String> that stores usernames. I need to pass this list to a method that only accepts String[] (an array of strings). I tried simply casting the type, but the compiler complains. Here's my code:
import java.util.ArrayList;\n\npublic class Main {\n public static void main(String[] args) {\n ArrayList<String> names = new ArrayList<>();\n names.add("Anna");\n names.add("Peter");\n names.add("Maria");\n\n // Trying to convert to array\n String[] namesArray = (String[]) names; // Compilation error!\n \n processNames(namesArray);\n }\n\n public static void processNames(S No answers yet.
Log in to leave an answer