在内部类中调用此实例

时间:2012-04-26 15:05:06

标签: java interface iterator nodes inner-classes

我正在编写一个节点类,我想创建一个内部节点迭代器类,到目前为止我写过:

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<E> node = this;

注释代码是用Node类编写的,我在Node类本身实现了Iterator,但是我想把它变成一个内部类,任何建议如何使它成为那样的?

1 个答案:

答案 0 :(得分:8)

只需写下:

Node<E> node = Node.this;

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