Write a Java program to convert a linked list to array list
The Java code provided demonstrates how to convert a LinkedList to an ArrayList using a constructor, and then iterate over the ArrayList to retrieve its elements.
- The code defines a class named LinkedList_ArrayList with a main method, which serves as the entry point for the Java program.
- Inside the main method, a new LinkedList object named linked_list is created with a type parameter of String, indicating that it will store strings as its elements.
- Strings such as "Java", "C", "Cpp", etc., are added to the linked_list using the add method, which appends the elements to the end of the list.
- The System.out.println statement is used to print the initial contents of the linked_list before any modifications.
- Next, a new ArrayList object named array_list is created with a type parameter of String, and the linked_list is passed as an argument to the ArrayList constructor. This creates a new ArrayList containing the same elements as the linked_list.
- The for-each loop is used to iterate over the array_list, and for each element in the array_list, the System.out.println statement is used to print the element.
- The output of the program will be the initial contents of the linked_list printed on the first line, followed by the elements of the array_list printed on separate lines.
Source Code
import java.util.*;
public class LinkedList_ArrayList
{
public static void main(String[] args)
{
LinkedList <String> linked_list = new LinkedList <String> ();
linked_list.add("Java");
linked_list.add("C");
linked_list.add("Cpp");
linked_list.add("Python");
linked_list.add("Php");
linked_list.add("Css");
linked_list.add("Html");
linked_list.add("MySql");
System.out.println("Given linked list: " + linked_list);
List<String> array_list = new ArrayList<String>(linked_list);
for (String s : array_list)
{
System.out.println(s);
}
}
}
Output
Given linked list: [Java, C, Cpp, Python, Php, Css, Html, MySql]
Java
C
Cpp
Python
Php
Css
Html
MySql