이 기사에서는 연결 목록을 배열로 변환하거나 그 반대로 변환하는 방법을 이해할 것입니다. 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]