Java如何將陣列轉換為集合?

2019-10-16 22:28:26

在Java程式設計中,如何將陣列轉換為集合?

以下範例演示使用Util類的Arrays.asList(name)方法將陣列轉換為集合。

package com.yiibai;

import java.util.*;
import java.io.*;

public class Array2Collection {
    public static void main(String args[]) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("How many elements you want to add to the array: ");
        int n = Integer.parseInt(in.readLine());
        String[] name = new String[n];

        System.out.println("Enter your elements: ");
        for (int i = 0; i < n; i++) {
            name[i] = in.readLine();
        }
        List<String> list = Arrays.asList(name);
        System.out.println();

        for (String li : list) {
            String str = li;
            System.out.print(str + " ");
        }
    }
}

上述程式碼範例將產生以下結果。

How many elements you want to add to the array: 
3
Enter your elements: 
10
20
30

10 20 30