Reputation: 21
I have a small program with an algorithm to iterate through n number of parcels to find a certain weight numWeight
. After each iteration, the weight of a parcel is increased. When a solution is found, the solution should be stored in the solutions
variable. As such, when a solution is found, (when currentWeight == numWeight
) I want the current instance of comb
to be stored in an index of the solutions
arraylist. However, when try and store comb
in solutions
, the instance stored continues to change with comb
. How would I get it so that solutions
could store an instance of comb
as it is at the time that line executes? The code snippet in question is as follows:
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();
}
}
}
Thanks!
Upvotes: 2
Views: 112
Reputation: 131376
You have to create a new BookCombination
object at each time you add one in the list.
Otherwise you use the same for next iterations.
Creating exactly the same object would not make really sense :
comb = new BookCombination(numParcels, mailClass);
I think that you should increment maybe the number of parcels or something in this way to test other combinations.
Try it :
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();
}
}
}
Upvotes: 1