- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Create an 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); }
- Related Articles
- How to create an array of Object in Java
- Remove a range of elements from a LinkedList in Java
- Convert LinkedList to an array in Java
- Get first and last elements from Java LinkedList
- Java Program to Remove elements from the LinkedList
- Java Program to Access elements from a LinkedList
- How to create a Queue from LinkedList in Java?
- Copy all elements of ArrayList to an Object Array in Java
- Copy all elements of Java HashSet to an Object Array
- Copy all elements of Java LinkedHashSet to an Object Array
- Copy all elements in Java TreeSet to an Object Array
- How to create an object from class in Java?
- Create Ennead Tuple from an array in Java
- Create KeyValue Tuple from an array in Java
- Create Decade Tuple from an array in Java

Advertisements