带有索引参数的java iterator

时间:2015-05-08 12:32:42

标签: java linked-list iterator

对于LinkedList的正常迭代器将是以下,但是,我们如何构建一个从指定索引开始返回迭代器的迭代器?我们如何建立:

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

谢谢! 普通的迭代器:

    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 */ }
    }

2 个答案:

答案 0 :(得分:4)

您可以调用正常的iterator()方法,然后多次调用next()

public Iterator<E> iterator(int index) {
    Iterator<E> iterator = iterator();
    for (int i = 0; i < index && iterator.hasNext(); i++) {
        iterator.next();
    }
    return iterator;
}

答案 1 :(得分:2)

这是如何实现此类interface的启动示例,但建议也创建或扩展适当的interface并使此对象实现此import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class IterableObject { private List<String> values = new ArrayList<String>(); public Iterator<String> getIterator(final int index) { Iterator<String> it = new Iterator<String>() { private int current = index; @Override public void remove() { // TODO Auto-generated method stub } @Override public String next() { String value = values.get(current); current++; return value; } @Override public boolean hasNext() { if(values.size() > current){ return true; }else{ return false; } } }; return it; } } 以进行约定

LinkedList

<强>更新

根据评论,我为public Iterator<String> getIterator(final int index) { Iterator<String> it = new Iterator<String>() { private Object currentObject = null; { /*initialize block where we traverse linked list that it will pointed to object at place index*/ System.out.println("initialize" + currentWord); for(int i = 0; currentObject.next != null && i < index; i++, currentObject = currentObject.next) ; } @Override public void remove() { // TODO Auto-generated method stub } @Override public String next() { Object obj = currentObject.next; currentObject = currentObject.next; return obj; } @Override public boolean hasNext() { return currentObject.next != null; } }; return it; }

编写了一个迭代器
Iterator

由于Anonymous classconstructor的对象,我们无法使用currentObject,但可以在初始化块中初始化它,请查看此答案:https://stackoverflow.com/a/362463/947111我们遍历它一次在开头(抱歉C风格)所以它会指向{{1}}。所有遗留代码都是自我解释的。