[英]Java Iterator - infinite loop
What am I doing wrong?我究竟做错了什么? Why does this iterator keep running?
为什么这个迭代器继续运行?
default List<T> greedyAlgorithm() {
List<T> lst = new ArrayList<>();
T element = selection().next();
while(selection().hasNext()) {
if(feasibility(lst ,element)) {
assign(lst, element);
} else {
element = selection().next();
}
if(solution(lst)){
return lst;
}
}
return null;
}
The feasibility function checks if the element is viable, if yes assign the element to the list.可行性 function 检查元素是否可行,如果是,则将元素分配给列表。 Then the solution checks if this is the 'algo' solution and returns the list, else check the next element in the list.
然后解决方案检查这是否是“算法”解决方案并返回列表,否则检查列表中的下一个元素。
next
should always be executed inside the loop. next
应该总是在循环内执行。
If the feasibility
condition isn't false
or solution
true, then it'll keep running without advancing.如果
feasibility
条件不为false
或solution
为真,那么它将继续运行而不推进。
I suggest rearranging the loop so you unconditionally call next
.我建议重新安排循环,以便您无条件调用
next
。
There may also be a problem if selection
returns a new Iterator
every call.如果
selection
每次调用都返回一个新的Iterator
,也可能会出现问题。
Perhaps something like this:也许是这样的:
default List<T> greedyAlgorithm() {
List<T> lst = new ArrayList<>();
for (
Iterator<T> selection = selection();
selection.hasNext();
) {
T element = selection.next();
if (feasibility(lst ,element)) {
assign(lst, element);
if (solution(lst)) {
return lst;
}
}
}
return null;
}
If selection()
returned an Iterable
you could use a posh for loop.如果
selection()
返回一个Iterable
你可以使用一个豪华的 for 循环。 Generally returning a type such as Iterable
that (kind of) doesn't change internal state is better than a type that does, such as Iterator
(although there is remove
so Iterable.iterator
isn't entirely innocent).通常返回诸如
Iterable
之类的(某种)不会改变内部 state 的类型比诸如Iterator
之类的类型要好(尽管有remove
所以Iterable.iterator
并非完全无辜)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.