gpt4 book ai didi

java - 列表过程中的无限循环

转载 作者:行者123 更新时间:2023-12-01 07:45:58 27 4
gpt4 key购买 nike

我有以下代码块:

ArrayList<ELPERouteStop> candidates = new ArrayList<>();
for (int i=0; i < metric.length;i++)
{

/*
* We get a from object for each row (customer) and a to object for the element
* of the matrix with the highest metric from the ith customer.
*/
ELPERouteStop from = all_stops.get(i);
ELPERouteStop to = all_stops.get(getMaxValue(metric[i]));
if(i==0)
{
candidates.add(from);
candidates.add(to);
}
for (int j=0; j < candidates.size();j++)
{
int k=0;
if (candidates.get(j) == from || candidates.get(j)==to)
{
k++;
}
if (k == 0)
{
candidates.add(from);
candidates.add(to);
}
}
}

问题似乎在于每次迭代时候选列表大小的变化。我需要将 from 和 to 对象插入到候选列表中,前提是它们尚不存在。因此,我在第二个 for 循环中进行检查。当我运行代码时,它似乎进入无限循环,但我找不到原因。预先感谢您!

最佳答案

您可以使用Collection#contains,而不是每次都迭代集合。

List<ELPERouteStop> candidates = new ArrayList<>();
for (int i=0; i < metric.length;i++) {

ELPERouteStop from = all_stops.get(i);
ELPERouteStop to = all_stops.get(getMaxValue(metric[i]));

if (!candidates.contains(from) && !candidates.contains(to)) {
candidates.add(from);
candidates.add(to);
}
}

或者,稍微更高效 - 取决于 getMaxValue 的速度:

for (int i=0; i < metric.length;i++) {

ELPERouteStop from = all_stops.get(i);
if (!candidates.contains(from)) {
ELPERouteStop to = all_stops.get(getMaxValue(metric[i]));
if (!candidates.contains(to)) {
candidates.add(from);
candidates.add(to);
}
}
}

关于java - 列表过程中的无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52604649/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com