在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