操作 ArrayList
在 Java 中,建立一個 ArrayList 資料結構並對其加入或移除物件是很常見的工作。在本練習中,你會建立一份購物清單(以 String 清單表示),並在清單上新增、移除與變更項目。
本練習屬於課程
Java 的資料型別與例外狀況
練習說明
- 匯入應用程式要使用的
ArrayList。 - 建立一個新的
String型別的ArrayList,並將變數shopList指向它。 - 在購物清單中再加入第二個
"milk"。 - 將購物清單中的
"bread"改為"rye-bread"。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
// Import ArrayList
____ ____.____.____;
public class Shopping {
public static void main(String[] args) {
// Create an ArrayList of Strings using parameterized constructor
____<____> shopList = ____ ____<____>();
shopList.add("milk");
shopList.add("eggs");
shopList.add("bread");
// Add milk to the list again
shopList.____("____");
System.out.println(shopList);
// Change bread to rye-bread in the list
shopList.____(____, "____");
shopList.remove("milk");
System.out.println(shopList);
System.out.println(shopList.size());
}
}