W
W
warchant2015-09-01 17:59:25
Java
warchant, 2015-09-01 17:59:25

How to implement an Iterator for your own List?

There is a native implementation of List in Java

class List<T> implements Iterable<T> {
    // code is here ...
    public Iterator<T> iterator() {
        // что нужно сюда писать?
    }

    class Node<T>{
    T value;  
    Node<T> next;
        // interface of Node is here.
    }
}

Do I need to implement my own class?
Iterator<T> implements java.util.Iterator<T>{}
Or is there some other way?
UPD:
I solved it like this:
@Override
    public Iterator<T> iterator() {
        return new Iterator<T>() {
            private Node<T> current = first;

            @Override
            public boolean hasNext() {
                return current.hasNext();
            }

            @Override
            public T next() throws IndexOutOfBoundsException {
                T result = current.value;
                if (!current.hasNext()) throw new IndexOutOfBoundsException("End of list.");
                current = current.next;
                return result;
            }
        };
    }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
kazmiruk, 2015-09-01
@warchant

Yes, you need to implement a class from Iterator and return an instance of that class in the iterator method. If you don’t want to bother, then you can immediately implement Iterator in your List, respectively, return this in iterator() and immediately add next, hasNext methods to it. Thus, you will have all the logic hidden in one class, but the object will be both iterable and iterator at the same time, which is not very good in my opinion.

A
abs0lut, 2015-09-01
@abs0lut

Here is the implementation for the first link in Google:

import java.util.Iterator;

public class SOList<Type> implements Iterable<Type> {

    private Type[] arrayList;
    private int currentSize;

    public SOList(Type[] newArray) {
        this.arrayList = newArray;
        this.currentSize = arrayList.length;
    }

    @Override
    public Iterator<Type> iterator() {
        Iterator<Type> it = new Iterator<Type>() {

            private int currentIndex = 0;

            @Override
            public boolean hasNext() {
                return currentIndex < currentSize && arrayList[currentIndex] != null;
            }

            @Override
            public Type next() {
                return arrayList[currentIndex++];
            }

            @Override
            public void remove() {
                throw new UnsupportedOperationException();
            }
        };
        return it;
    }
}

Here are more examples
And here with an explanation
Well, the last one
That's it, this one is definitely the last one ...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question