Java 示例 - 数组到集合

  • 问题描述

    如何将数组转换为集合?
  • 解决方案

    以下示例演示了将数组转换为 Java Util 类的集合 Arrays.asList(name) 方法。
    
    import java.util.*;
    import java.io.*;
    public class ArrayToCollection{
       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];
          
          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:
    red white green
    red white green