📜  如何在Java中将 LinkedList 转换为数组?

📅  最后修改于: 2022-05-13 01:54:27.073000             🧑  作者: Mango

如何在Java中将 LinkedList 转换为数组?

给定Java中的 Linked List,任务是将此 LinkedList 转换为 Array。

例子:

Input: LinkedList: ['G', 'e', 'e', 'k', 's'] 
Output: Array: ['G', 'e', 'e', 'k', 's'] 

Input: LinkedList: [1, 2, 3, 4, 5]
Output: Array: [1, 2, 3, 4, 5] 

方法:

  1. 获取链表
  2. 使用 toArray() 方法将 LinkedList 转换为 Object 数组。
  3. 使用 Arrays.copyOf() 方法将 Object 数组转换为所需的类型数组。
  4. 返回打印数组

下面是上述方法的实现:

// Java program to convert
// LinkedList to Array
  
import java.util.*;
  
public class GFG {
  
    // Function to convert LinkedList to Array
    public static  Object[] convertLinkedListToArray(LinkedList linkedList)
    {
  
        // Converting LinkedList to Array
        Object[] array = linkedList.toArray();
  
        return array;
    }
  
    public static void main(String args[])
    {
        // Creating linked list
        LinkedList
            linkedList = new LinkedList();
  
        // Adding elements to the linked list
        linkedList.add("G");
        linkedList.add("e");
        linkedList.add("e");
        linkedList.add("k");
        linkedList.add("s");
  
        // Print the LinkedList
        System.out.println("Linked list: "
                           + linkedList);
  
        // Converting LinkedList to Object Array
        Object[] objArray = convertLinkedListToArray(linkedList);
  
        // Convert Object[] to String[]
        String[] array = Arrays.copyOf(objArray,
                                       objArray.length,
                                       String[].class);
        // Print the String Array
        System.out.println("Array: "
                           + Arrays.toString(array));
    }
}
输出:
Linked list: [G, e, e, k, s]
Array: [G, e, e, k, s]