laker001
laker001

Reputation: 417

Trouble implementing ArrayList Iterator in Java

Here's my implementation of an iteratorover an ArrayList:

public class MyClass {

    List<E> list = new ArraList<E>();

public Iterator<E> iterator() {

        return new MyIterator<E>();
    }

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

     int index;

        public MyIterator() {

            index = 0;

        }

        public E next() {

            if (hasNext()){
            index++;
            return list.get(index + 1);
        }

        else
            throw new NoSuchElementException();
        }

        public boolean hasNext() {

        if ((list.get(index + 1) != null) && (index < list.size() -1)){
                index++;
                return true;
            }
            else
                return false;
        }

        public void remove() {
            throw new UnsupportedOperationException();
        }

    }

}

However, although the logic looks alright to me, this implementation is wrong, because it does not work properly.

My question is: what am i doing wrong, and how can i change it in order for it to work properly?

UPDATE:

public E next() {

        if (index == 0) {
            index++;
            return list.get(0);
        }

        else if (hasNext()) {
            index++;
            return list.get(index);
        }

        else
            throw new NoSuchElementException();
    }

I've managed to, somehow, make it work, but now the next method is skipping indexes of the array. How can i fix this ?

Upvotes: 0

Views: 70

Answers (1)

NoseKnowsAll
NoseKnowsAll

Reputation: 4623

Without an example of how you're using this iterator, it's hard to give you advice. That being said, here's at least two things you are doing incorrect. In your next() method, you have

index++;
return list.get(index + 1);

So you will first be incrementing the index, and then returning the NEXT index. This should result in an out of bounds exception. Change it to return list.get(index);

Secondly, your hasNext() method isn't ordered correctly. That is, you should check whether your next index is valid before checking whether the next object exists or not. Re-order your if statement to:

if ((index < list.size() -1) && (list.get(index + 1) != null))

Also get rid of the index++; line in hasNext(). The method should just be checking for validity, not actually changing your current index. That should happen in next().

Upvotes: 1

Related Questions