java 如何让列表迭代器从给定的索引开始?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30146484/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to have List Iterator start at a given index?
提问by user3769402
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:
我有一个链表,我需要创建在列表中的给定点返回迭代器的方法。我目前有一个从头开始的迭代器:
public Iterator<E> iterator( )
{
return new ListIterator();
}
All I have for the other one is:
我对另一个的所有是:
public Iterator<E> iterator(int x )
{
return new ListIterator();
}
I'm not sure how to go about utilizing the given position(x) that won't affect my ListIterator constructor which starts at head.
我不确定如何利用给定的 position(x) 不会影响我从头开始的 ListIterator 构造函数。
I tried using a for loop to get to "x" but realized that wouldn't tell the iterator to start there, so I'm quite stumped.
我尝试使用 for 循环到达“x”,但意识到这不会告诉迭代器从那里开始,所以我很困惑。
Edit:
编辑:
public ListIterator()
{
current = head; // head in the enclosing list
}
回答by Radiodef
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.
否则,您可以将列表遍历到第 x 个节点,但没有理由不能这样做。
回答by ShellFish
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
简单地使用listIterator(index);
从方法List
,其中index
是一个int
类似的起始索引。编辑:在你的情况下,它会是
List<...> list = ...;
return list.listIterator(x);
回答by user3769402
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.
鉴于更大的范围,我可能已经添加了一个构造函数,但无法改变太多,这是最好的。