IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 移动开发 -> Guava中AbstractIterator源码分析 -> 正文阅读

[移动开发]Guava中AbstractIterator源码分析

今天阅读Guava源码发现一个通用的迭代器设计。

package com.google.common.collect;

import static com.google.common.base.Preconditions.checkState;

import com.google.common.annotations.GwtCompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.NoSuchElementException;


public abstract class AbstractIterator<T> extends UnmodifiableIterator<T> {
  private State state = State.NOT_READY;

  /** Constructor for use by subclasses. */
  protected AbstractIterator() {}

  private enum State {
    /** We have computed the next element and haven't returned it yet. */
    READY,

    /** We haven't yet computed or have already returned the element. */
    NOT_READY,

    /** We have reached the end of the data and are finished. */
    DONE,

    /** We've suffered an exception and are kaput. */
    FAILED,
  }

  private T next;

  /**
   * Returns the next element. <b>Note:</b> the implementation must call {@link
   * #endOfData()} when there are no elements left in the iteration. Failure to
   * do so could result in an infinite loop.
   *
   * <p>The initial invocation of {@link #hasNext()} or {@link #next()} calls
   * this method, as does the first invocation of {@code hasNext} or {@code
   * next} following each successful call to {@code next}. Once the
   * implementation either invokes {@code endOfData} or throws an exception,
   * {@code computeNext} is guaranteed to never be called again.
   *
   * <p>If this method throws an exception, it will propagate outward to the
   * {@code hasNext} or {@code next} invocation that invoked this method. Any
   * further attempts to use the iterator will result in an {@link
   * IllegalStateException}.
   *
   * <p>The implementation of this method may not invoke the {@code hasNext},
   * {@code next}, or {@link #peek()} methods on this instance; if it does, an
   * {@code IllegalStateException} will result.
   *
   * @return the next element if there was one. If {@code endOfData} was called
   *     during execution, the return value will be ignored.
   * @throws RuntimeException if any unrecoverable error happens. This exception
   *     will propagate outward to the {@code hasNext()}, {@code next()}, or
   *     {@code peek()} invocation that invoked this method. Any further
   *     attempts to use the iterator will result in an
   *     {@link IllegalStateException}.
   */
  protected abstract T computeNext();

  /**
   * Implementations of {@link #computeNext} <b>must</b> invoke this method when
   * there are no elements left in the iteration.
   *
   * @return {@code null}; a convenience so your {@code computeNext}
   *     implementation can use the simple statement {@code return endOfData();}
   */
  @CanIgnoreReturnValue
  protected final T endOfData() {
    state = State.DONE;
    return null;
  }

  @CanIgnoreReturnValue // TODO(kak): Should we remove this? Some people are using it to prefetch?
  @Override
  public final boolean hasNext() {
    checkState(state != State.FAILED);
    switch (state) {
      case DONE:
        return false;
      case READY:
        return true;
      default:
    }
    return tryToComputeNext();
  }

  private boolean tryToComputeNext() {
    state = State.FAILED; // temporary pessimism
    next = computeNext();
    if (state != State.DONE) {
      state = State.READY;
      return true;
    }
    return false;
  }

  @CanIgnoreReturnValue // TODO(kak): Should we remove this?
  @Override
  public final T next() {
    if (!hasNext()) {
      throw new NoSuchElementException();
    }
    state = State.NOT_READY;
    T result = next;
    next = null;
    return result;
  }

  /**
   * Returns the next element in the iteration without advancing the iteration,
   * according to the contract of {@link PeekingIterator#peek()}.
   *
   * <p>Implementations of {@code AbstractIterator} that wish to expose this
   * functionality should implement {@code PeekingIterator}.
   */
  public final T peek() {
    if (!hasNext()) {
      throw new NoSuchElementException();
    }
    return next;
  }
}

有两个实例字段:

private State state = State.NOT_READY;
private T next;

state有四种状态

private enum State {
    /** We have computed the next element and haven't returned it yet. */
    READY,

    /** We haven't yet computed or have already returned the element. */
    NOT_READY,

    /** We have reached the end of the data and are finished. */
    DONE,

    /** We've suffered an exception and are kaput. */
    FAILED,
  }

所有的迭代器都需要实现hasNext和next这两个方法。

这个类的设计思路是:

每次执行hasNext的时候如果 next的值准备好了就返回true。没有准备好就会尝试着去寻找这个next的值。在寻找的过程中先假设会寻找失败将state设置为FAILED。寻找到了这个next的值就把state设置为ready。这个寻找的过程是一个抽象的过程,所以这一个类有一个抽象的方法:

 protected abstract T computeNext();

在返回值赋值给next.如果在寻找的过程中到达了序列的结尾在computeNext()这个方法里面需要把state的值设置为Done。这就是这个抽象方法的语义。

在状态为ready只会执行next方法就是把next返回出来同时,设置next值为空,然设置state为NOT_READY。此时又可以进行下一轮的hasNext和next过程了。

这里给出一个基于这个类的最简单的实现。实现了computeNext的方法完全符合语义。寻找得到的时候返回这个值,在序列终止的时候设置状态为Done

 public static Iterator<String> skipNulls(final Iterator<String> in) {
     return new AbstractIterator<String>() {
       protected String computeNext() {
          while (in.hasNext()) {
            String s = in.next();
           if (s != null) {
              return s;
          }
         }
         return endOfData();
       }
     };

Guava中的Splitter就是基于这样的一个模式设计的。Splitter认为被切割的字符串是一个待返回的迭代器。

  移动开发 最新文章
Vue3装载axios和element-ui
android adb cmd
【xcode】Xcode常用快捷键与技巧
Android开发中的线程池使用
Java 和 Android 的 Base64
Android 测试文字编码格式
微信小程序支付
安卓权限记录
知乎之自动养号
【Android Jetpack】DataStore
上一篇文章      下一篇文章      查看所有文章
加:2022-05-07 11:18:35  更:2022-05-07 11:19:28 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/25 0:56:20-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码