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
Convert LinkedList to ArrayList in Java
A LinkedList can be converted into an ArrayList by creating an ArrayList such that the parameterized constructor of the ArrayList initialises it with the elements of the LinkedList.
A program that demonstrates this is given as follows −
Example
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class Demo {
public static void main(String[] args) {
LinkedList<String> l = new LinkedList<String>();
l.add("Orange");
l.add("Apple");
l.add("Peach");
l.add("Guava");
l.add("Pear");
List<String> aList = new ArrayList<String>(l);
System.out.println("The ArrayList elements are: ");
for (Object i : aList) {
System.out.println(i);
}
}
}
Output
The ArrayList elements are: Orange Apple Peach Guava Pear
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("Orange");
l.add("Apple");
l.add("Peach");
l.add("Guava");
l.add("Pear");
An ArrayList aList is created and it is initialised using the elements of the LinkedList using a parameterized constructor. Then the ArrayList is displayed using a for loop. A code snippet which demonstrates this is as follows −
List<String> aList = new ArrayList<String>(l);
System.out.println("The ArrayList elements are: ");
for (Object i : aList) {
System.out.println(i);
}Advertisements