public static void 迭代器例子() {
List<String> ls = new ArrayList<>();
// 添加元素
ls.add("l1");
ls.add("l2");
ls.add("l3");
// 獲取實現迭代器接口的對象
Iterator<String> I = ls.iterator();
// 循環遍歷迭代器(是否存在下一個)
while (I.hasNext()) {
// 獲取下一個元素
String s = I.next();
if (s.equals("l1")) {
System.out.print("移除");
// 移除當前返回的元素
I.remove();
// 不能調用兩次會報錯
// I.remove();
}
System.out.println(s);
}
System.out.println("--------使用增強for循環-------");
// foreach循環遍歷的元素實現了iterable接口
for (String s1 : ls) {
System.out.println(s1);
}
I = ls.iterator();
System.out.println("--------使用lambda-------");
I.forEachRemaining(s -> {
System.out.println(s);
System.out.print(" ");
});
}