【问题标题】:call this instance in an inner class在内部类中调用此实例
【发布时间】:2012-05-07 08:21:00
【问题描述】:

我正在写一个节点类,我想做一个内部节点迭代器类,到目前为止我已经写了:

import java.util.Iterator;
import java.util.NoSuchElementException;

public class Node<E> {
  E data;
  Node<E> next;
  int current = 0;

  public Node(E data, Node<E> next){
    this.data = data;
    this.next = next;
  }

  public void setNext(Node<E> next){
    this.next = next;
  }

  private class NodeIterator implements Iterator {

    /*@Override
    public boolean hasNext() {      
      Node<E> node = this;
      for(int i=1; i<current; i++){
        node = node.next;
      }
      if(node.next==null){
        current = 0;
        return false;
      }
      current++;
      return true;
    }*/

    @Override
    public boolean hasNext() {
      // code here
    }

    /*public Node<E> next() {       
      if(next==null){
        throw new NoSuchElementException();
      }
      Node<E> node = this;
      for(int i=0; i<current && node.next!=null; i++){
        node = node.next;
      }
      return node;
    }*/

    @Override
    public Node<E> next() {
      // code here
    }

    @Override
    public void remove() {
      throw new UnsupportedOperationException();
    }
  }
}

我想在 NodeIterator 中创建一个节点对象,如下所示:Node&lt;E&gt; node = this;

注释的代码是用Node类编写的,我在Node类本身中实现了Iterator,但我想把它变成一个内部类,有什么建议吗?

【问题讨论】:

  • 所以要访问外层节点?试试Node&lt;E&gt; node = Node.this;。另请注意,您可能希望在迭代器中缓存下一个节点,而不是从第一个节点迭代到当前节点。

标签: java interface iterator nodes inner-classes


【解决方案1】:

只写:

Node<E> node = Node.this;

它访问封闭的外部节点实例

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-21
    • 1970-01-01
    • 2017-05-30
    • 2011-05-03
    • 1970-01-01
    • 2015-12-04
    • 1970-01-01
    相关资源
    最近更新 更多