1. Introduction
In Java, ArrayList and LinkedList are two commonly used classes for storing lists of objects. Sometimes, you might need to convert an ArrayList to a LinkedList. This blog post demonstrates how to achieve this conversion in a simple manner.
2. Program Steps
1. Initialize an ArrayList and populate it with some elements.
2. Print out the original ArrayList.
3. Convert the ArrayList to a LinkedList.
4. Print out the resulting LinkedList.
3. Code Program
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class ConvertArrayListToLinkedList {
public static void main(String[] args) {
// Step 1: Initialize an ArrayList and populate it with some elements
List<String> arrayList = new ArrayList<>();
arrayList.add("Java");
arrayList.add("Python");
arrayList.add("C++");
// Step 2: Print out the original ArrayList
System.out.println("Original ArrayList: " + arrayList);
// Step 3: Convert the ArrayList to a LinkedList
List<String> linkedList = new LinkedList<>(arrayList);
// Step 4: Print out the resulting LinkedList
System.out.println("Converted LinkedList: " + linkedList);
}
}
Output:
Original ArrayList: [Java, Python, C++] Converted LinkedList: [Java, Python, C++]
4. Step By Step Explanation
Step 1: An ArrayList named arrayList is initialized and populated with the elements "Java", "Python", and "C++".
Step 2: The content of the original ArrayList is printed to the console, displaying: "Original ArrayList: [Java, Python, C++]".
Step 3: The ArrayList is converted to a LinkedList named linkedList by passing arrayList as a parameter to the LinkedList constructor. This creates a new LinkedList containing the same elements as the original ArrayList.
Step 4: The content of the resulting LinkedList is printed to the console, confirming that it contains the same elements as the ArrayList. The output is: "Converted LinkedList: [Java, Python, C++]".