将LinkedList转换成数组,反之亦然Java程序


在本文中,我们将学习如何将LinkedList转换成数组,以及反之亦然。java.util.LinkedList类的操作符合我们对双向链表的预期。索引进入列表的操作将从起始或结束遍历列表,以距离指定索引更近者为准。

下面是一个演示 −

假设我们的输入是

The list is defined as: [Java, Python, Scala, Mysql]

期望的输出将是

The result array is: Java Python Scala Mysql

算法

Step 1 - START
Step 2 - Declare namely
Step 3 - Define the values.
Step 4 - Create a list and add elements to it using the ‘add’ method.
Step 5 - Display the list on the console.
Step 6 - Create another empty list of previous list size.
Step 7 - Convert it into array using the ‘toArray’ method.
Step 8 - Iterate over the array and display the elements on the console.
Step 9 - Stop

示例1

在这里,我们将列表转换成一个数组。

Open Compiler
import java.util.LinkedList; public class Demo { public static void main(String[] args) { System.out.println("The required packages have been imported"); LinkedList<String> input_list= new LinkedList<>(); input_list.add("Java"); input_list.add("Python"); input_list.add("Scala"); input_list.add("Mysql"); System.out.println("The list is defined as: " + input_list); String[] result_array = new String[input_list.size()]; input_list.toArray(result_array); System.out.print("\nThe result array is: "); for(String elements:result_array) { System.out.print(elements+" "); } } }

Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

输出

The required packages have been imported
The list is defined as: [Java, Python, Scala, Mysql]

The result array is: Java Python Scala Mysql

示例2

在这里,我们将数组转换成一个列表。

Open Compiler
import java.util.Arrays; import java.util.LinkedList; public class Demo { public static void main(String[] args) { System.out.println("The required packages have been imported"); String[] result_array = {"Java", "Python", "Scala", "Mysql"}; System.out.println("The elements of the result_array are defined as: " + Arrays.toString(result_array)); LinkedList<String> result_list= new LinkedList<>(Arrays.asList(result_array)); System.out.println("\nThe elements of the result list are: " + result_list); } }

输出

The required packages have been imported
The elements of the result_array are defined as: [Java, Python, Scala, Mysql]

The elements of the result list are: [Java, Python, Scala, Mysql]

更新日期:2022-3-30

298次浏览

开启你的 职业

通过完成课程获得认证

开始
广告