Java LinkedList toArray() Method
Example
Get an array from an 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);
}
}
}
Definition and Usage
The toArray()
method returns an array containing all of the items in the list.
If no argument is passed then the type of the returned array will be Object
. If an array is passed as an argument then this method will return an array with the same data type.
If the array in the argument is large enough to contain all of the list items then this method will return the argument itself after writing the list items into it.
Syntax
One of the following:
public Object[] toArray()
public T[] toArray(T[] array)
T
refers to the data type of items in the list.
Parameter Values
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. |
Technical Details
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 .NullPointerException - If the argument is null .
|
More Examples
Example
Specify the return type of toArray()
:
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
LinkedList<String> cars = new LinkedList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
String[] carsArray = new String[4];
carsArray = cars.toArray(carsArray);
for(String item : carsArray) {
System.out.println(item);
}
}
}
Related Pages
❮ LinkedList Methods