How to have List Iterator start at a given index?

前端 未结 3 1308
予麋鹿
予麋鹿 2021-01-14 12:45

I have a linked list and I need to make method that returns an iterator at a given point in the list. I currently have an iterator that starts at the head:

p         


        
相关标签:
3条回答
  • 2021-01-14 13:18

    Simply use the listIterator(index); method from List, in which index is an int resembling the starting index. Edit: in your case it would be

    List<...> list = ...;
    return list.listIterator(x);
    
    0 讨论(0)
  • 2021-01-14 13:22

    So I ended up going with this.

    public Iterator<E> iterator(int x){
    
        Iterator<E> it = new ListIterator();
    
        for (; x > 0; --x){
            it.next(); 
        }
        return it;
    }
    

    Given more range I might have added a constructor but without being able to change much this worked the best.

    0 讨论(0)
  • 2021-01-14 13:24

    Without seeing your implementation, the trivial way to do this is:

    public Iterator<E> iterator(int x) {
        if (x < 0 || this.size() < x) {
            throw new IndexOutOfBoundsException();
        }
    
        Iterator<E> it = new ListIterator();
    
        for (; x > 0; --x) {
            it.next(); // ignore the first x values
        }
        return it;
    }
    

    Otherwise, you could traverse the list to the xth node, but there's no reason you can't do it this way.

    0 讨论(0)
提交回复
热议问题