我有一个小程序,其中包含一个算法,用于遍历 n 个包裹以找到特定重量 numWeight
。每次迭代后,包裹的重量都会增加。找到解决方案后,解决方案应存储在 solutions
变量中。因此,当找到解决方案时,(当 currentWeight == numWeight
时)我希望 comb
的当前实例存储在 solutions< 的索引中
数组列表。但是,当尝试将 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();
}
}
}
谢谢!
最佳答案
每次在列表中添加一个对象时,您都必须创建一个新的 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();
}
}
}
关于java - 将不断变化的变量的实例存储在java中的另一个变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45534576/