Converting LinkedList to array is very easy. You can convert a LinkedList of any type (such as double, String, int etc) to an array of same type. In this tutorial we will see an example of such type of conversion.
Example
Here we are converting a LinkedList of strings to String Array (LinkedList to String[]). At the end of the program we have mentioned how to convert a list of any other type such as double, int etc to corresponding array type.
import java.util.LinkedList; public class ConvertExample { public static void main(String[] args) { //Creating and populating LinkedList LinkedList<String> linkedlist = new LinkedList<String>(); linkedlist.add("Harry"); linkedlist.add("Maddy"); linkedlist.add("Chetan"); linkedlist.add("Chauhan"); linkedlist.add("Singh"); //Converting LinkedList to Array String[] array = linkedlist.toArray(new String[linkedlist.size()]); //Displaying Array content System.out.println("Array Elements:"); for (int i = 0; i < array.length; i++) { System.out.println(array[i]); } } }
Output:
Array Elements: Harry Maddy Chetan Chauhan Singh
As you can see we are having the same elements in array that we had in the LinkedList.
Note:
In the above example we have taken a LinkedList of Strings, however if you have a LinkedList of different type then you can just change the conversion logic like this.
For LinkedList conversion logic would be:
Double[] array = linkedlist.toArray(new Double[linkedlist.size()]);
Similarly for LinkedList conversion logic would be:
Integer[] array = linkedlist.toArray(new Integer[linkedlist.size()]);
More about toArray() method from Javadoc:
public T[] toArray(T[] a)
: It returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array. If the list fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this list.
If the list fits in the specified array with room to spare (i.e., the array has more elements than the list), the element in the array immediately following the end of the list is set to null. (This is useful in determining the length of the list only if the caller knows that the list does not contain any null elements.)
Leave a Reply