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(); } Listlist = 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