简体   繁体   中英

Having trouble making my own iterator for a collections class

I'm getting the error "Iterator cannot be resolved to a type". I'm trying to take the storage class and add the code necessary to implement java's Collections class. I dont think i'm allowed to import Iterator, i think i need to make my own.

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;
            }
        };
    }
}

您需要import java.util.Iterator;

This code isn't even wrong; check out the Iterator methods:

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

Your Iterator does not implement the java.util.Iterator interface; using the same name doth not make it one.

Look at your method:

public int hasNext()

The java.util.Iterator hasNext() returns a boolean.

This is utterly wrong.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM