The toArray() method of the LinkedList class converts the current Linked List object into an array of object type and returns it. This array contains all the elements in this list in correct order (from first element to last element). It acts as a bridge between array-based and collection-based APIs.
So, convert LinkedList to array -
Instantiate LinkedList class.
Fill it using the add() method.
Call the toArray() method on the linked list created above and retrieve the object array.
Convert each element of the object array to a string.
Real-time demonstration
import java.util.Arrays; import java.util.LinkedList; public class LinkedListToArray { public static void main(String[] args) { LinkedList <String> list = new LinkedList<String>(); //Instantiating an ArrayList object list.add("JavaFX"); list.add("Java"); list.add("WebGL"); list.add("OpenCV"); list.add("OpenNLP"); list.add("JOGL"); list.add("Hadoop"); list.add("HBase"); list.add("Flume"); list.add("Mahout"); list.add("Impala"); Object[] objectAarray = list.toArray(); int length = objectAarray.length;; String [] stringArray = new String[length]; for(int i =0; i < length; i++) { stringArray[i] = (String) objectAarray[i]; } System.out.println("Contents of the array: \n"+Arrays.toString(stringArray)); } }
Contents of the array: [JavaFX, Java, WebGL, OpenCV, OpenNLP, JOGL, Hadoop, HBase, Flume, Mahout, Impala]
You can also pass new String[0] Pass to the toArray() method to get the string array directly.
Real-time demonstration< /p>
import java.util.Arrays; import java.util.LinkedList; public class LinkedListToArray { public static void main(String[] args) { LinkedList <String> list = new LinkedList<String>(); //Instantiating an ArrayList object list.add("JavaFX"); list.add("Java"); list.add("WebGL"); list.add("OpenCV"); list.add("OpenNLP"); list.add("JOGL"); list.add("Hadoop"); list.add("HBase"); list.add("Flume"); list.add("Mahout"); list.add("Impala"); String[] stringArray = list.toArray(new String[0]); System.out.println("Contents of the array: \n"+Arrays.toString(stringArray)); } }
Contents of the array: [JavaFX, Java, WebGL, OpenCV, OpenNLP, JOGL, Hadoop, HBase, Flume, Mahout, Impala]
The above is the detailed content of How to convert LinkedList to Array in Java?. For more information, please follow other related articles on the PHP Chinese website!