Retrieve an array from a LinkedList:
import java.util.LinkedList;
public class Main { public static void main(String[] args) { LinkedList cars = new LinkedList(); cars.add(“Volvo”); cars.add(“BMW”); cars.add(“Ford”); cars.add(“Mazda”);
Object[] carsArray = cars.toArray();
for(Object item : carsArray) { System.out.println(item); } } } |
The toArray() method retrieves an array containing all elements from the list.
If no argument is provided, the returned array type will be Object. However, if an array is specified as an argument, the method will return an array of the same type.
If the provided array is large enough to accommodate all list elements, the method populates it with the list items and returns the same array.
Choose one from the following:
public Object[] toArray() |
public T[] toArray(T[] array) |
T represents the data type of items in the list.
Parameter |
Description |
array |
Optional. An array which specifies the data type of the returned array and will be returned by the method if it has enough space for the items in the list. If the array is not large enough then the method returns a new array of the same data type. |
Returns: |
An array containing all of the elements of the LinkedList in order. |
Throws: |
ArrayStoreException – If the type of the array is not compatible with the type of the LinkedList. |
Define the return type of toArray():
import public
|