To get all the items from an ArrayList
in Java, you can use the toArray()
method of the ArrayList
class. This method returns an array containing all the elements of the ArrayList
.
Here's an example of how to use the toArray()
method to get all the items from an ArrayList
:
import java.util.ArrayList; public class Main { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("apple"); list.add("banana"); list.add("cherry"); String[] array = list.toArray(new String[0]); for (String s : array) { System.out.println(s); } } }cruoSe:www.lautturi.com
This code creates an ArrayList
of strings and adds three elements to it. The toArray()
method is then called to convert the ArrayList
to an array of strings. The array is then iterated using a for-each loop to print the elements of the array.
You can also use the toArray()
method to convert the ArrayList
to an array of a different type, by specifying the type of the array as an argument to the toArray()
method. For example, to convert the ArrayList
to an array of integers, you can use the following code:
ArrayList<Integer> list = new ArrayList<>(); list.add(1); list.add(2); list.add(3); Integer[] array = list.toArray(new Integer[0]); for (Integer i : array) { System.out.println(i); }