To convert an ArrayList
to an array in Java, you can use the toArray
method of the ArrayList
class, which returns an array containing the elements of the list in the same order.
Here is an example of how you can use the toArray
method to convert an ArrayList
to an array:
ArrayList<String> list = new ArrayList<>(); list.add("apple"); list.add("banana"); list.add("cherry"); String[] array = list.toArray(new String[0]);
This code creates an ArrayList
of strings and adds three elements to it. Then, it calls the toArray
method and passes an empty array of strings as an argument. The toArray
method returns an array of strings containing the elements of the list, which is assigned to the array
variable.
You can also use the toArray
method to convert an ArrayList
to an array of a different type, by passing an array of the desired type as an argument. For example:
ArrayList<String> list = new ArrayList<>(); list.add("apple"); list.add("banana"); list.add("cherry"); Object[] array = list.toArray();
This code creates an ArrayList
of strings and converts it to an array of objects using the toArray
method. The result is stored in the array
variable.
Note that the toArray
method returns an array of the type specified in the argument, so you may need to cast the elements of the array to the desired type if necessary.
ArrayList<String> list = new ArrayList<>(); list.add("apple"); list.add("banana"); list.add("cherry"); Object[] array = list.toArray(); String s = (String) array[0];
This code converts an ArrayList
of strings to an array of objects, and then casts the first element of the array to a string. The result is stored in the s
variable.