1. Iterator 接口
public interface Iterator<E> {
boolean hasNext();
E next();
default void remove() {
throw new UnsupportedOperationException("remove");
}
default void forEachRemaining(Consumer<? super E> action) {
Objects.requireNonNull(action);
while (hasNext())
action.accept(next());
}
}
1.1 Iterator遍历
@Test
public void test() {
List<String> list = new ArrayList<>();
list.add("111");
list.add("222");
list.add("333");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String next = iterator.next();
}
}
多层遍历
@Test
public void test() {
Map<Long, Set<String>> map = new HashMap<>();
map.put(1001L, new HashSet<>(Arrays.asList("aaa", "bbb")));
map.put(1002L, new HashSet<>(Arrays.asList("ccc")));
// Iterator<Set<String>> iterator = map.values().iterator();
String next = map.values().iterator().next().iterator().next();
// 输出 next: aaa
}
1.2 遍历时注意事项
迭代过程中不能进行删除、添加操作,会抛异常java.util.ConcurrentModificationException
@Test
public void test() {
List<String> list = new ArrayList<>();
list.add("111");
list.add("222");
list.add("333");
for (String str : list) {
if ("111".equals(str)) {
list.remove("111");
// list.add("444");
}
}
}
报错原因:
private class Itr implements Iterator<E> {
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
改为iterator.remove()
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
if ("111".equals(iterator.next())) {
iterator.remove();
}
}
2. Iterable 接口
public interface Iterable<T> {
Iterator<T> iterator();
default void forEach(Consumer<? super T> action) {
Objects.requireNonNull(action);
for (T t : this) {
action.accept(t);
}
}
}
实现 Iterable 接口,就拥有了获取迭代器的能力
2.1 集合里的迭代器
Collection 继承了 Iterable 接口
public interface Collection<E> extends Iterable<E> {
Iterator<E> iterator();
}
public interface List<E> extends Collection<E> {
Iterator<E> iterator();
}
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable {
public Iterator<E> iterator() {
return new Itr();
}
// 内部类实现了 Iterator
private class Itr implements Iterator<E> {
public boolean hasNext() {}
public E next() {}
public void remove() {}
}
}
2.2 Iterable 存在的意义
解耦,有些集合有多个 Iterator 内部类,可以获取不同的 Iterator 执行不一样的操作,比如ArrayList,LinkedList
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable {
public ListIterator<E> listIterator() {
return new ListItr(0);
}
public Iterator<E> iterator() {
return new Itr();
}
private class Itr implements Iterator<E> {}
private class ListItr extends Itr implements ListIterator<E> {}
}
网友评论