java库中的迭代器模式应用及其源码示例
时间: 2023-09-02 12:14:57 浏览: 65
Java库中迭代器模式的应用非常广泛,以下是一些常见的使用场景:
1. 遍历集合类中的元素,如ArrayList、LinkedList、HashSet、TreeSet等。
2. 遍历Map中的键值对,如HashMap、TreeMap等。
3. 遍历文件中的数据,如BufferedReader等。
下面是一个简单的示例代码,演示了如何使用Java中的迭代器模式来遍历ArrayList中的元素:
```java
import java.util.ArrayList;
import java.util.Iterator;
public class IteratorDemo {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Java");
list.add("Python");
list.add("C++");
Iterator<String> it = list.iterator();
while (it.hasNext()) {
String s = it.next();
System.out.println(s);
}
}
}
```
在上面的代码中,我们首先创建了一个ArrayList对象,并向其中添加了三个元素。然后,我们通过调用list.iterator()方法获取了一个迭代器对象it,并使用while循环遍历ArrayList中的元素。在循环体中,我们通过it.next()方法获取了下一个元素,并将其打印出来。
Java中的迭代器模式的源码实现非常复杂,具体实现方式与不同的集合类有关。以ArrayList为例,其迭代器实现类是Itr,代码如下:
```java
private class Itr implements Iterator<E> {
int cursor; // 下一个要返回的元素的索引
int lastRet = -1; // 上一个返回的元素的索引,初始值为-1
int expectedModCount = modCount; // ArrayList的修改次数
public boolean hasNext() {
return cursor != size; // 判断是否还有下一个元素
}
@SuppressWarnings("unchecked")
public E next() {
checkForComodification(); // 检查ArrayList是否被修改
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification(); // 检查ArrayList是否被修改
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
```
在上面的代码中,我们可以看到Itr类实现了Iterator接口,其中包含了hasNext()、next()、remove()等方法。在next()方法中,我们首先检查ArrayList是否被修改,然后获取下一个元素的索引,并返回该元素。在remove()方法中,我们首先检查上一个返回的元素的索引是否合法,然后调用ArrayList的remove()方法删除该元素。在以上代码中,还包含了一些用于检查ArrayList是否被修改的方法,以确保迭代器的正确性。