2013-11-23 50 views
0

我的名单看起来是这样的:有麻烦创建我自己的列表迭代器

public class SList<A> implements Iterable<A> 
{ 
    private Listelem head; 
    private Listelem current; 
    private boolean listEmpty; 

    private class Listelem 
    { 
     private A value; 
     private Listelem next; 

     private Listelem(A val) 
     { 
      this.value = val; 
      this.next = null; 
     } 
     private Listelem() 
     { 
      this.next = null; 
     } 

     public void setValue(A val) 
     { 
      this.value = val; 
     } 
     public A getValue() 
     { 
      return this.value; 
     } 
     public void setSuccessor(Listelem next) 
     { 
      this.next = next; 
     } 
     public Listelem getSuccessor() 
     { 
      return this.next; 
     } 
    } 
} 

我要为这个列表创建一个迭代器,但我有一些麻烦。 在SLIST我这样做:

@Override 
public Iterator<A> iterator() { 
    Iterator<A> it = new Iterator<A>() { 

     this.current = this.head; 

     @Override 
     public boolean hasNext() { 
      boolean hasNext = true; 
      if(this.current.getSucessor == null) 
      { 
       hasNext = false; 
      } 
      return hasNext; 
     } 

     @Override 
     public A next() { 
      A next  = this.current.getValue; 
      this.current = this.current.getSuccessor(); 
      return next; 
     } 

     @Override 
     public void remove() { 
      // TODO Auto-generated method stub 
     } 
    }; 
    return it; 
} 

我不能老是参考this.current或this.head。我想知道为什么这不起作用,因为我在同一班。

+0

太多的代码,你至少可以指向你坚持的位?它不让你参考它? – FaddishWorm

回答

1

你只是忘了在你的Iterator中声明一个current字段。列表头应该用SList.this.head或简单地用head来访问。 this引用迭代器实例。不在列表中。你应该使用一个非匿名类:

@Override 
public Iterator<A> iterator() { 
    return new MyListIterator(); 
} 

private class MyListIterator implements Iterator<A> { 
    private Listelem current; 

    private MyListIterator() { 
     this.current = head; 
    } 

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

    @Override 
    public A next() { 
     A next  = this.current.getValue; 
     this.current = this.current.getSuccessor(); 
     return next; 
    } 

    @Override 
    public void remove() { 
     // TODO Auto-generated method stub 
    } 
} 
1

您正在创建一个带有new的新迭代器,因此您处于班级的匿名内部类中。试用SList.this.current

0

尝试SList.this.head。您正试图引用您定义的Iterator子类中不存在的字段。

取而代之,您要参考封闭的SList类的head字段。这就是您可以通过使用我在开始发布的代码片段获得的内容。

+0

迭代器的当前元素不应该在列表中。它应该是迭代器对象的一个​​字段。 –