
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Create Object Array from Elements of LinkedList in Java
An object array can be created from the elements of a LinkedList using the method java.util.LinkedList.toArray(). This method returns the object array with all the LinkedList elements in the correct order.
A program that demonstrates this is given as follows.
Example
import java.util.LinkedList; public class Demo { public static void main(String[] args) { LinkedList<String> l = new LinkedList<String>(); l.add("Amy"); l.add("Sara"); l.add("Joe"); l.add("Betty"); l.add("Nathan"); Object[] objArr = l.toArray(); System.out.println("The object array elements are: "); for (Object i: objArr) { System.out.println(i); } } }
Output
The output of the above program is as follows −
The object array elements are: Amy Sara Joe 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
LinkedList<String> l = new LinkedList<String>(); l.add("Amy"); l.add("Sara"); l.add("Joe"); l.add("Betty"); l.add("Nathan");
The LinkedList.toArray()method is used to convert the LinkedList into an object array objArr[]. Then the object array is displayed using a for loop. A code snippet which demonstrates this is as follows
Object[] objArr = l.toArray(); System.out.println("The object array elements are: "); for (Object i: objArr) { System.out.println(i); }
Advertisements