設定 Collection
接下來你會更深入認識 Collection 與 Map 資料結構。不過在此之前,先練習其中一種 Collection 型別所需的匯入、建立與型別參數設定,具體來說是 ArrayList。
本練習屬於課程
Java 的資料型別與例外狀況
練習說明
- 匯入 Java Collections Framework 套件中的「所有」型別。
- 建立名為
list的變數,使用泛型在ArrayList上指定String,用來儲存字串的ArrayList。 - 使用帶有型別參數的建構子
ArrayList<String>,將list指定為新的ArrayList實例。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
// Import all types from Collections Framework package
import ____.____.____;
public class HelloWorld {
public static void main(String[] args) {
// Create a variable for a group of Strings
____<____> list;
// Set the variable to new ArrayList
list = ____ ____<____>();
list.add("hello");
System.out.println(list);
}
}