Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Chương trình Java chuyển đổi LinkedList thành Array và ngược lại


Trong bài viết này, chúng ta sẽ hiểu cách chuyển đổi LinkedList thành Array và ngược lại. Lớp java.util.LinkedList thực hiện các thao tác như mong đợi cho danh sách liên kết kép (doubly-linked list). Các thao tác truy xuất theo chỉ số sẽ duyệt list từ đầu hoặc cuối, tùy phía gần chỉ số chỉ định hơn.

Minh họa dưới đây:

Giả sử đầu vào là:

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

Đầu ra mong muốn:

The result array is: Java Python Scala Mysql

Thuật toán

Bước 1 - BẮT ĐẦU 
Bước 2 - Khai báo biến 
Bước 3 - Định nghĩa giá trị 
Bước 4 - Tạo list, thêm phần tử bằng 'add' 
Bước 5 - Hiển thị list 
Bước 6 - Tạo list rỗng khác cùng kích thước 
Bước 7 - Chuyển thành mảng bằng 'toArray' 
Bước 8 - Duyệt mảng hiển thị phần tử 
Bước 9 - DỪNG

Ví dụ 1

Chuyển List thành Array.

import java.util.LinkedList; 

public class Demo { 
    public static void main(String[] args) { 
        System.out.println("The required packages have been imported"); 
        LinkedList 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 + " "); 
        } 
    } 
}

Kết quả

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

Ví dụ 2

Chuyển Array thành List.

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 result_list = new LinkedList<>(Arrays.asList(result_array)); 
        System.out.println("\nThe elements of the result list are: " + result_list); 
    } 
}

Kết quả

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]