Scott
Scott

Reputation: 455

Point an iterator to an object Java?

I'm having a bit of trouble working this out, it may be because I last did this sort of stuff in C++ and it's slightly different but I'm having the following problem.

I'm having to write a custom ArrayList class and an associated Iterator. I have implemented the basic class structure which looks like the following:

public class MyArrayList<T> implements Iterable<T> {

protected T[] array;
private MyIterator<T> itr = new MyIterator<T>();

public MyArrayList() {
    array = (T[]) new Object[10];
}

public MyArrayList(int i) {
    array = (T[]) new Object[i];
}

@Override
public Iterator<T> iterator() {
    return itr;
}

private class MyIterator<T> implements Iterator<T> {

    @Override
    public void remove() {

    }

    @Override
    public T next() {
        return null;
    }

    @Override
    public boolean hasNext() {
        return true;
    }
}

}

Obviously I'm still adding code but I've just implemented what needs to be there for now to get rid of all the error messages. What I'm attempting to do now is link my iterator called itr to the first element in the array in my list constructor.

Like in C++ with pointers do I need to point the iterator to the first item in my collection, the whole idea of an iterator is that it knows it's current position but I'm not sure if I have to explicitly tell it where to start? Hope this makes sense thanks.

Upvotes: 0

Views: 405

Answers (1)

ajb
ajb

Reputation: 31689

You will need to declare the MyIterator class inside MyArrayList. The effect is that when an instance of MyIterator is created, it will be associated with an instance of the MyArrayList class, and it will be able to access the members of the MyArrayList (including the private members). That way, your iterator will be able to access array and whatever variable you define for the current length.

As Josh said, instead of declaring an itr variable, iterator() should use new MyIterator. The new MyIterator object will automatically be associated with the same MyArrayList object that's calling new MyIterator (there's a syntax for associating it with a different MyArrayList but you won't need it here, I think). Inside MyIterator, the methods will be able to access array and other MyArrayList fields. The constructor for MyIterator will be responsible for whatever initialization is needed; you'll probably want a "current index" field of some sort in MyIterator, and the constructor will initialize it.

More on nested classes: http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html .

Upvotes: 1

Related Questions