- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert LinkedList to an array in Java
A LinkedList can be converted into an Array in Java using the method java.util.LinkedList.toArray(). This method has a single parameter i.e. the Array into which the LinkedList elements are to stored and it returns the Array with all the LinkedList elements in the correct order.
A program that demonstrates this is given as follows.
Example
import java.util.LinkedList; import java.util.List; public class Demo { public static void main(String[] args) { List<String> l = new LinkedList<String>(); l.add("John"); l.add("Sara"); l.add("Susan"); l.add("Betty"); l.add("Nathan"); String[] str = l.toArray(new String[0]); System.out.println("The String Array elements are: "); for (int i = 0; i < str.length; i++) { System.out.println(str[i]); } } }
The output of the above program is as follows −
The String Array elements are: John Sara Susan Betty Nathan
Now let us understand the above program.
The LinkedList l is created. Then LinkedList.add() is used to add the elements to the LinkedList. A code snippet which demonstrates this is as follows
List<String> l = new LinkedList<String>(); l.add("John"); l.add("Sara"); l.add("Susan"); l.add("Betty"); l.add("Nathan");
The LinkedList.toArray()method is used to convert the LinkedList into a string array str[]. Then the string array is displayed using a for loop. A code snippet which demonstrates this is as follows
- Related Articles
- How to convert LinkedList to Array in Java?
- Java Program to Convert the LinkedList into an Array and vice versa
- Convert LinkedList to ArrayList in Java
- Program to convert ArrayList to LinkedList in Java
- Create an object array from elements of LinkedList in Java
- How to convert an object array to an integer array in Java?
- Convert a Vector to an array in Java
- Convert an ArrayList to an Array with zero length Array in Java
- Program to convert Stream to an Array in Java
- How to convert an array to string in java?
- Java program to convert an Array to Set
- How to convert an object to byte array in java?
- How to convert an array to a list in Java?
- How to convert an Array to a Set in Java?
- How do you convert an ArrayList to an array in Java?
