Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java iterator with index parameter

hi a normal iterator for a LinkedList would be the following, however, how do we build an iterator that returns an iterator starting at a specified index? How do we build:

public Iterator<E>iterator(int index)???  

thanks! normal Iterator:

    public Iterator<E> iterator( )
    {
        return new ListIterator();
    }

private class ListIterator implements Iterator<E>
    {
        private Node current;

        public ListIterator()
        {
            current = head; // head in the enclosing list
        }
        public boolean hasNext()
        {
            return current != null;
        }
        public E next()
        {
            E ret = current.item;
            current = current.next;
            return ret;
        }
        public void remove() { /* omitted because optional */ }
    }
like image 550
Katherine Avatar asked Jun 22 '26 18:06

Katherine


1 Answers

Well you could just call the normal iterator() method, then call next() that many times:

public Iterator<E> iterator(int index) {
    Iterator<E> iterator = iterator();
    for (int i = 0; i < index && iterator.hasNext(); i++) {
        iterator.next();
    }
    return iterator;
}
like image 104
Jon Skeet Avatar answered Jun 25 '26 07:06

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!