You can convert an ArrayList<String> object to a String[] array in Java using the toArray() method of the ArrayList class. Here's how you can do it:
java
import java.util.ArrayList;
import java.util.Arrays;
public class ArrayListToStringArrayExample {
public static void main(String[] args) {
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("Hello");
arrayList.add("World");
arrayList.add("Java");
String[] stringArray = arrayList.toArray(new String[0]);
System.out.println("Converted String Array: " + Arrays.toString(stringArray));
}
}
In this example:
- We create an
ArrayListcalledarrayListcontaining some strings. - We use the
toArray()method of theArrayListclass to convert it to aString[]array. - We provide an empty
Stringarray as an argument to thetoArray()method. The type and length of this array will be used to create the resultingString[]array.
The stringArray will now hold the same elements as the ArrayList, and you can manipulate it as a regular array.
Please note that the resulting String[] array is a new array, separate from the original ArrayList. Any modifications to the stringArray will not affect the original ArrayList.
Comments
Post a Comment