0

The list over which I want to iterate, contains an Array.

What I am trying to do is to make it possible to create an Iterator within the Iterator, so that I am able to iterate over the array in every Listelement.

I tried it this way:

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

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

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

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

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

    @Override
    public void remove() 
    {
        Listelem tmp = head;
        while( tmp.getSuccessor().getSuccessor() != this.current ) 
        {
            tmp = tmp.getSuccessor();
        }
        tmp.setSuccessor(this.current);
    }

    @Override
    public Iterator<B> iterator() {
        return new MyInnerListIterator();
    }

    private class MyInnerListIterator implements Iterator<B>
    {
        private int currentIndex = 0;
        private B[] array = current.getAssoc();
        @Override
        public boolean hasNext() {
            return currentIndex < array.length && array[currentIndex] != null;
        }

        @Override
        public B next() {
            return array[currentIndex++];
        }

        @Override
        public void remove() {

        }

    }
}

The problem is, when I am creating the first Iterator with iterator() the object does not contain the method iterator().

Can somebody explain to my why this is not working, and how to do it different?

1
  • 1
    Array can be easily iterated without using iterator. Commented Nov 24, 2013 at 19:25

1 Answer 1

1

The problem is that iterator returns an Iterator, even though in this case it happens to also be a MyListIterator. Class Iterator does not have an iterator() function. You need to have iterator() return a MyListIterator, so that you can use methods not in the Iterator interface. It is likely simpler however, to simply use a for:in loop:

List<Object[]> list = ....
for (Iterator<Object[]> it = list.iterator(); it.hasNext();) {
    Object[] arr = it.next();
    for (Object o : arr) {
        ...
    }
}

And if you don't need to remove elements from the list, then you can replace the iterator use with another for:in

Sign up to request clarification or add additional context in comments.

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.