【问题标题】:Having trouble making my own iterator for a collections class无法为集合类制作自己的迭代器
【发布时间】:2010-12-09 01:50:47
【问题描述】:

我收到错误“无法将迭代器解析为类型”。我正在尝试使用存储类并添加实现 java 的 Collections 类所需的代码。 我不认为我可以导入 Iterator,我想我需要自己制作。

public class storage {
    private Object[] data = new Object[256];
    // Don't allow access to anything not yet stored
    private int nextEmptySlot = 0;
    private int i=0;
    public Object begin(){
        return data[0];
    }
    public Object end(){
        return data[nextEmptySlot];
    }

    //class Iterator() {
        // public Storage data;
    //}

    public Iterator iterator() {

        // returns a class that iterates over the data array
        return new Iterator() {
            public Object remove(){
                for(int j=i+1 ; j<=nextEmptySlot-1 ; j++) {
                    this.data[j-1] = this.data[j];
                }
                return (this.data.data[i]);
            }

            public int hasNext(){
                if(this.data.data[i+1] != null) return 1;
                else return 0;
            }

            public Object next(){
                i++;
                if (hasNext()==1){
                    return this.data.data[i];
                }
                else if (hasNext()==0){
                    throw UnsupportedOperationException();       
                }
                return this;
            }
        };
    }
}

【问题讨论】:

  • 一般情况下,类名以大写字母开头...Storage

标签: java class collections iterator


【解决方案1】:

你需要import java.util.Iterator;

【讨论】:

    【解决方案2】:

    这段代码甚至没有错;查看迭代器方法:

    http://download.oracle.com/javase/1.4.2/docs/api/java/util/Iterator.html

    您的迭代器没有实现 java.util.Iterator 接口;同名不合。

    看看你的方法:

    public int hasNext()
    

    java.util.Iterator hasNext() 返回一个布尔值。

    这是完全错误的。

    【讨论】:

      猜你喜欢
      • 2015-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-29
      • 2017-12-08
      • 2018-12-13
      • 1970-01-01
      • 2016-11-19
      相关资源
      最近更新 更多