Problem Statement: Write a Java program to Convert an ArrayList of strings into a string array.
Here’s a Java program that demonstrates how to convert an ArrayList
of strings into a string array. I’ll provide an explanation of the program’s logic.
package com.javacodepoint.collection;
import java.util.ArrayList;
public class ArrayListToStringArrayDemo {
public static void main(String[] args) {
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("Hello");
arrayList.add("World");
arrayList.add("Java");
arrayList.add("Programming");
// Converting ArrayList to String array
String[] stringArray = arrayList.toArray(new String[arrayList.size()]);
// Printing the string array
System.out.println("String Array:");
for (String str : stringArray) {
System.out.println(str);
}
}
}
OUTPUT:
String Array:
Hello
World
Java
Programming
Explanation:
- Creating the ArrayList: We create an
ArrayList
namedarrayList
and populate it with some strings. - Converting to String Array: We use the
toArray()
method of theArrayList
class to convert thearrayList
into a string array. The method requires an argument that specifies the target array type and size. In this case, we create a newString
array with the same size as theArrayList
. - Printing the String Array: We iterate through the
stringArray
and print each string using afor-each
loop.
The toArray()
method converts the ArrayList
of strings into a string array, allowing you to work with the data in an array format.
See also: Create a stack using an ArrayList.