java - 返回一个迭代器是什么意思? java

标签 java iterator

我必须编写一个实现 Iterable 接口(interface)的类。我对返回迭代器对象的含义感到困惑。迭代器只是遍历列表的元素,那么我如何将其作为对象返回呢?我会返回一个能够迭代的列表还是什么?当迭代器所做的只是遍历或更改其他对象中的数据时,它怎么可能是一个对象?

最佳答案

这是一个非常简单的列表示例。它将列表表示为链接元素。 迭代器对象被创建为一个匿名内部类,将当前元素作为状态。每次调用 iterator() 都会创建一个新的迭代器对象。

import java.util.Iterator;

public class SimplisticList<T> implements Iterable<T> {

  /*
   * A list element encapsulates a data value and a reference to the next
   * element.
   */
  private static class Element<T> {
    private T data;
    private Element<T> next;

    Element(T data) {
      this.data = data;
      next = null;
    }

    public T getData() {
      return data;
    }

    public Element<T> getNext() {
      return next;
    }

    public void setNext(Element<T> next) {
      this.next = next;
    }

  }

  // We only need a reference to the head of the list.
  private Element<T> first = null;

  // The list is empty if there is no first element.
  public boolean isEmpty() {
    return first == null;
  }

  // Adding a new list element.
  // For an empty list we only have to set the head.
  // Otherwise we have to find the last element to add the new element.
  public void add(T data) {
    if(isEmpty()) {
      first = new Element<T>(data);
    } else {
      Element<T> current = first;
      while(current.getNext() != null) {
        current = current.getNext();
      }
      current.setNext(new Element<T>(data));
    }
  }

  @Override
  public Iterator<T> iterator() {
    // Create an anonymous implementation of Iterator<T>.
    // We need to store the current list element and initialize it with the
    // head of the list.
    // We don't implement the remove() method here. 
    return new Iterator<T>() {
      private Element<T> current = first;

      @Override
      public boolean hasNext() {
        return current != null;
      }

      @Override
      public T next() {
        T result = null;
        if(current != null) {
          result = current.getData();
          current = current.getNext();
        }
        return result;
      }

      @Override
      public void remove() {
        // To be done ...
        throw new UnsupportedOperationException();
      }
    };
  }

}

关于java - 返回一个迭代器是什么意思? java ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26566641/

相关文章:

java - 在 Intellij IDEA 中打开 Gradle 项目时出现问题

c# - Objective-C 中是否有与 C# 的 yield 关键字相似的地方

c++ - 在没有分配的情况下加入并重新拆分两个 std::list

c++ - {} 是传递给需要迭代器(代表某个容器的 std::end() )的函数的有效参数吗?

c++ - 如何在一段时间内从 multimap 中删除多个项目?

java - 使用预签名 URL 从 S3 下载对象

java - 循环 Picasso 加载 url 图片

java不合理的jtextfield大小问题

java - GCJ 抛出错误 : "Undefined reference to main" when compiling

C++,为二叉树实现自定义迭代器(长)