本文目录导读:

我来详细讲解Java中的迭代器模式及其在集合遍历中的应用。
迭代器模式概述
迭代器模式提供一种方法顺序访问一个聚合对象中的各个元素,而不暴露其内部表示。
核心角色
- Iterator(迭代器接口):定义访问和遍历元素的接口
- ConcreteIterator(具体迭代器):实现迭代器接口
- Aggregate(聚合接口):定义创建迭代器的方法
- ConcreteAggregate(具体聚合类):实现聚合接口
Java集合框架中的迭代器
Java的java.util.Iterator接口是实现迭代器模式的标准方式。
Iterator接口定义
public interface Iterator<E> {
boolean hasNext(); // 判断是否有下一个元素
E next(); // 返回下一个元素
void remove(); // 移除当前元素(可选操作)
}
基本使用示例
1 使用Iterator遍历List
import java.util.*;
public class IteratorExample {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("Java");
list.add("Python");
list.add("C++");
list.add("JavaScript");
// 使用迭代器遍历
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String element = iterator.next();
System.out.println(element);
}
}
}
2 使用Iterator遍历Set
public class SetIteratorExample {
public static void main(String[] args) {
Set<Integer> numbers = new HashSet<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.add(40);
Iterator<Integer> iterator = numbers.iterator();
while (iterator.hasNext()) {
Integer num = iterator.next();
System.out.println(num);
}
}
}
3 使用Iterator遍历Map
public class MapIteratorExample {
public static void main(String[] args) {
Map<String, Integer> scores = new HashMap<>();
scores.put("张三", 95);
scores.put("李四", 87);
scores.put("王五", 92);
// 遍历键值对
Iterator<Map.Entry<String, Integer>> iterator =
scores.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Integer> entry = iterator.next();
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
迭代器的高级用法
1 使用增强for循环
public class EnhancedForExample {
public static void main(String[] args) {
List<String> list = Arrays.asList("A", "B", "C", "D");
// 增强for循环底层使用迭代器
for (String element : list) {
System.out.println(element);
}
}
}
2 使用forEachRemaining方法(Java 8+)
public class ForEachRemainingExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
Iterator<Integer> iterator = numbers.iterator();
// 使用Lambda表达式处理剩余元素
iterator.forEachRemaining(num -> {
System.out.println(num * 2);
});
}
}
3 在遍历过程中删除元素
public class SafeRemoveExample {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
list.add("orange");
list.add("grape");
// 安全删除元素
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String fruit = iterator.next();
if (fruit.startsWith("a")) {
iterator.remove(); // 使用迭代器的remove方法
}
}
System.out.println(list); // 输出: [banana, orange, grape]
}
}
自定义迭代器实现
// 自定义集合类
class BookCollection implements Iterable<String> {
private String[] books;
private int size = 0;
public BookCollection(int capacity) {
books = new String[capacity];
}
public void addBook(String book) {
if (size < books.length) {
books[size++] = book;
}
}
@Override
public Iterator<String> iterator() {
return new BookIterator();
}
// 内部迭代器类
private class BookIterator implements Iterator<String> {
private int currentIndex = 0;
@Override
public boolean hasNext() {
return currentIndex < size && books[currentIndex] != null;
}
@Override
public String next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
return books[currentIndex++];
}
@Override
public void remove() {
// 实现删除逻辑
if (currentIndex <= 0) {
throw new IllegalStateException();
}
// 移动数组元素
System.arraycopy(books, currentIndex,
books, currentIndex - 1,
size - currentIndex);
books[--size] = null;
currentIndex--;
}
}
}
// 使用自定义迭代器
public class CustomIteratorExample {
public static void main(String[] args) {
BookCollection library = new BookCollection(5);
library.addBook("Java编程思想");
library.addBook("设计模式");
library.addBook("重构:改善既有代码");
// 使用迭代器遍历
for (String book : library) {
System.out.println(book);
}
// 显式使用迭代器
Iterator<String> iterator = library.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
ListIterator(列表迭代器)
ListIterator是Iterator的子接口,提供了双向遍历能力:
public class ListIteratorExample {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("First");
list.add("Second");
list.add("Third");
// 正向遍历
ListIterator<String> listIterator = list.listIterator();
while (listIterator.hasNext()) {
int index = listIterator.nextIndex();
String element = listIterator.next();
System.out.println("Index " + index + ": " + element);
}
System.out.println("---反向遍历---");
// 反向遍历
while (listIterator.hasPrevious()) {
int index = listIterator.previousIndex();
String element = listIterator.previous();
System.out.println("Index " + index + ": " + element);
}
// 在指定位置开始遍历
ListIterator<String> fromIndex = list.listIterator(1);
while (fromIndex.hasNext()) {
System.out.println(fromIndex.next());
}
}
}
迭代器的优缺点
优点
- 统一遍历接口:无论集合类型如何,遍历方式相同
- 支持多种遍历方式:可同时进行多个遍历
- 简化集合接口:集合无需提供遍历方法
- 安全删除:提供了安全的元素删除机制
缺点
- 单向遍历限制:基本Iterator只能单向遍历
- 快速失败机制:结构修改会抛出ConcurrentModificationException
- 性能开销:相比直接访问数组有一定性能损耗
最佳实践
注意事项
- 避免在迭代过程中修改集合结构(除了使用迭代器的remove方法)
- 优先使用增强for循环(代码更简洁)
- 需要删除元素时使用显式迭代器
- 考虑使用Java 8的Stream API(更函数式的方式)
public class BestPractices {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
// 推荐:增强for循环
for (String item : list) {
System.out.println(item);
}
// 需要删除时:显式迭代器
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
if (iterator.next().contains("delete")) {
iterator.remove();
}
}
// Java 8+:使用Stream
list.stream()
.filter(s -> s.length() > 3)
.forEach(System.out::println);
}
}
迭代器模式是Java集合框架的核心设计模式之一,了解其工作原理对于编写高效、安全的Java代码非常重要。
版权声明:NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播