ในบทความนี้ เราจะเข้าใจวิธีการแปลงรายการที่เชื่อมโยงเป็นอาร์เรย์ และในทางกลับกัน การดำเนินการคลาส 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
เราแปลงรายการเป็นอาร์เรย์
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+" ");
}
}
} ผลลัพธ์
The required packages have been imported The list is defined as: [Java, Python, Scala, Mysql] The result array is: Java Python Scala Mysql
ตัวอย่างที่ 2
ที่นี่ เราแปลงอาร์เรย์เป็นรายการ
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]