1. Introduction

In Java, both LinkedList and ArrayList are implementations of the List interface. You may need to convert a LinkedList to an ArrayList for various reasons, such as taking advantage of ArrayList‘s faster random access times. This conversion can be done using the constructor of the ArrayList class that accepts a Collection object.

2. Program Steps

1. Create a LinkedList and add some elements to it.

2. Create an ArrayList by passing the LinkedList to the constructor of ArrayList.

3. Print the ArrayList to verify that elements have been transferred.

3. Code Program

import java.util.ArrayList;
import java.util.LinkedList;

public class LinkedListToArrayList {

    public static void main(String[] args) {

        // Step 1: Create a LinkedList and add some elements to it
        LinkedList<String> linkedList = new LinkedList<>();
        linkedList.add("Apple");
        linkedList.add("Banana");
        linkedList.add("Cherry");

        // Step 2: Create an ArrayList by passing the LinkedList to the constructor of ArrayList
        ArrayList<String> arrayList = new ArrayList<>(linkedList);

        // Step 3: Print the ArrayList
        System.out.println(arrayList);
    }
}

Output:

[Apple, Banana, Cherry]

4. Step By Step Explanation

Step 1: A LinkedList named linkedList is created and some elements are added to it.

Step 2: An ArrayList named arrayList is created. The LinkedList is passed to the constructor of the ArrayList, thereby converting it to an ArrayList.

Step 3: The ArrayList is printed to verify that it contains the same elements as the LinkedList, demonstrating that the conversion was successful.