0

I am trying to implement an Iterator with Iterable in Java, here is what I have so far:

public class keysIterator<A> implements Iteratble<A<{
     A[] elements;
     int nextElement; 

keysIterator(A[] elements, int nextElement) {
    this.elements = elements;
    this.nextElement = 0;
}

public boolean hasNext() {
    return this.nextElement < elements.length;
}

public A next() {
    A result = elements[nextElement];
    nextElement = nextElement + 1;
    return result;
}

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

public Iterator<A> iterator() {
    // TODO Auto-generated method stub
}

}

I need help writing the remove and iterator methods, any assistance is greatly appericated.

Thank you.

0

3 Answers 3

4

Having an Iterator implement Iterable doesn't make sense to me

Something Iterable has an iterator() method, that returns an Iterator.

Also an iterator usually doesn't hold the data but refers to someother instance that has the data.

So usually

class Foo implements Iterable
{
    public Iterator iterator() {
        return new FooIterator();
    }
}

class FooIterator implements Iterator {
     // with methods as you've defined them
}
Sign up to request clarification or add additional context in comments.

Comments

4

You are mixing up implementation of the Iterator interface with your Iterable class. Try this:

public class KeysIterable<A> implements Iterable<A> {
    A[] elements;
    int nElements;

    private class KeysIterator<A> implements Iterator<A> {
        int nextElement = 0;

        public boolean hasNext() {
            return nextElement < nElements;
        }

        public A next() {
            A result = elements[nextElement];
            nextElement = nextElement + 1;
            return result;
        }

        public void remove() {
            if (nextElement < nElements - 1) {
                System.arraycopy(elements, nextElement + 1,
                    elements, nextElement, nElements - nextElement - 1);
            }
            nElements--;
        }
    }

    public Iterator<A> iterator() {
        return new KeysIterator<A>();
    }

    public KeysIterable() {

    }

    // other methods
}

It would probably be better to implement your Iterable class using an ArrayList instead of a generic array.

Comments

2

Use an ArrayList instead of an array, so you can just do:

public Iterator<A> iterator() {
    return elements.iterator();
}

If you really want an array, you can always do:

public Iterator<A> iterator() {
    return Arrays.asList(elements).iterator();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.