← 從零開始學 Java
第 67 課,共 88 課 · 10 XP
集合
理論與題目說明
機器翻譯,尚未經母語人士審閱。
所有的串列和集合都實作共同的介面 Collection<E>:
Collection<String> c = new ArrayList<>(); // <>——型別從左邊的宣告推斷
c.add("sword");
c.addAll(List.of("shield", "potion"));
c.remove("shield");
c.contains("sword") // true
c.size(), c.isEmpty()
c.retainAll(other) // 只留下 other 裡也有的(交集)
c.removeAll(other) // 刪掉 other 裡有的所有東西(差集)
c.clear()
for (String s : c) …
好習慣是讓變數用介面的型別(Collection、List、Map),而不是類別:這樣就能
輕鬆換掉實作。
題目。 兩行——兩個玩家的物品(用空白分隔的詞)。輸出:依第一個人物品的
順序列出共同的物品(retainAll)、只有第一個人有的物品(removeAll),以及原本物品的數量。
結果是空的就輸出 -。