我有一个带有算法的小程序来遍历n个包裹以找到一定的权重numWeight
。每次迭代后,包裹的重量都会增加。找到解决方案后,解决方案应存储在solutions
变量中。因此,当找到解决方案时,(当currentWeight == numWeight
时)我希望comb
的当前实例存储在solutions
arraylist的索引中。但是,在comb
中尝试并存储solutions
时,存储的实例将继续随comb
更改。我如何得到它以便solutions
可以存储comb
的实例,就像该行执行时一样?有问题的代码段如下:
public void solution2(){
BookCombination comb = new BookCombination(numParcels, mailClass);
ArrayList<BookCombination> solutions = new ArrayList<>();
int currentWeight;
while (!stopCalc){
currentWeight = comb.getWeight();
if (currentWeight == 0){
break;
} else if (currentWeight == numWeight){
solutions.add(comb);
comb.increaseWeight();
} else {
comb.increaseWeight();
}
}
}
谢谢!
答案 0 :(得分:1)
每次在列表中添加一个对象时,都必须创建一个新的BookCombination
对象
否则,您将在下一次迭代中使用相同的内容。
创建完全相同的对象并不合理:
comb = new BookCombination(numParcels, mailClass);
我认为你应该以这种方式增加包裹或其他东西的数量来测试其他组合。
试一试:
public void solution2(){
BookCombination comb = new BookCombination(numParcels, mailClass);
ArrayList<BookCombination> solutions = new ArrayList<>();
int currentWeight;
while (!stopCalc){
currentWeight = comb.getWeight();
if (currentWeight == 0){
break;
} else if (currentWeight == numWeight){
solutions.add(comb);
comb = new BookCombination(numParcels++, mailClass); // change here
} else {
comb.increaseWeight();
}
}
}