操作 HashSet
建立一個用來存放身高(單位為英吋、型別為 Integer)的 HashSet,加入一些新的身高,並將其中一個身高替換為 null(用來驗證 Set 可以包含 null 物件)。
本練習屬於課程
Java 的資料型別與例外狀況
練習說明
- 匯入
HashSet以便在應用程式中使用。 - 建立一個新的
Integer型別的HashSet,並指定給變數heights。 - 將新的身高
64加入heights清單。 - 將
64替換為null。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
// Import HashSet
mport java.____.____;
public class Sizes {
public static void main(String[] args) {
// Create a HashSet of Integer using parameterized constructor
____<____> heights = new ____<____>();
heights.add(72);
// Add 64 to the set
heights.____(____);
heights.add(66);
heights.remove(64);
// Add null to the set
heights.____(____);
System.out.println(heights);
}
}