Java 的輸入/輸出與串流
Alex Liu
Software Development Engineer
HashSet 範例import java.util.HashSet;public class SampleHashSetData { public static void main(String[] args) { HashSet<String> fruits = new HashSet<>();fruits.add("Apple"); fruits.add("Banana");} }
{Apple, Banana}
For-Each 迴圈for (type x: collection){}List、Set、Map 等fruits:[Apple, Banana]。for (String x : fruits) {
System.out.println(x);
}
Apple
Banana
Iterator<>:支援 List、Set、Queue 等Iterator 類別import java.util.Iterator;// 建立樣本集合 `fruits` 的 `Iterator` 物件 `it` Iterator<String> it = fruits.iterator(); // 使用 `.hasNext()` 檢查是否還有元素 while (it.hasNext()) { // 使用 `.next()` 取得元素 System.out.print(it.next());}
Apple Banana
.remove() 搭配 Iterator 刪除元素$$
Iterator<String> it = fruits.iterator();
while (it.hasNext()) {
String fruit = it.next();
if (fruit.startsWith("A")) {
// 若元素以 `A` 開頭則移除
it.remove();
}
}
// fruits 現在只包含 "Banana"
刪除前:
System.out.println(fruits);
[Apple, Banana]
刪除後:
System.out.println(fruits);
[Banana]
確保安全刪除並避免 ConcurrentModificationException

For-Each 迴圈List(ArrayList、LinkedList)Set(HashSet、TreeSet、LinkedHashSet)Queue(PriorityQueue)Stack(Stack)Map刪除元素IteratorList(ArrayList、LinkedList)Set(HashSet、TreeSet、LinkedHashSet)Queue(PriorityQueue)Stack(Stack)Map(需使用 keySet().iterator、values().iterator 或 entrySet().iterator)刪除元素Java 的輸入/輸出與串流