我正在尝试将对象添加到arraylist中。这些对象都不包含任何静态字段或静态方法,但是当更新arraylist时,所有元素都会包含“' new'值。此外,每次循环时都会创建一个新实例,所以我不认为我一直在添加相同的对象。
ArrayList<Integer> rewards = new ArrayList<Integer>();
ArrayList<ArrayList<Route>> neighbours = new ArrayList<ArrayList<Route>>();
for(int i=0; i<10; i++)
{
Generate1Neighbour neighbour = new Generate1Neighbour(testDataFile,amp2Solution,randomGenerator,i);
System.out.println("Generated neighbour (Reward " + getSolutionReward(neighbour.solution)+ "): " + neighbour.solution.toString());
rewards.add(getSolutionReward(neighbour.solution));
neighbours.add(neighbour.solution);
}
testDataFile和amp2Solution在循环期间保持不变。
当我打印生成的邻居时,我可以看到在每次循环迭代中创建了一个不同的邻居。然而,在此循环之后,邻居包含10个相同的元素。
奖励确实包含10个不同的值。 在Generate1Neighbour类中,没有字段或方法是静态的。
此处,解决方案定义如下:
public ArrayList<Route> solution;
在Generate1Neighbour类中,使用了多种方法来更新解决方案。
我可以做错什么?
编辑: getSolutionReward方法如下:
public static int getSolutionReward(ArrayList<Route> solution)
{
int totalReward = 0;
for(Route route : solution)
{
totalReward += route.getReward();
}
return totalReward;
}
amp2solution是一个ArrayList。在Generate1Neighbour的构造函数中,变量&#39;解决方案&#39;设置为等于传递给构造函数的amp2solution。这个解决方案&#39;变量在Generate1Neighbour类中的许多方法中更新。
Generate1Neighbour的构造函数如下:
public Generate1Neighbour(DataFile testDataFile, ArrayList<Route> Sol, Random randomGen, int q_tabu) throws IOException
{
System.out.println("Starting Tabu procedure ");
neighbourhoodSize = "Small";
solution = Sol;
S_Comp = new ArrayList<MyNodesData>();
startPoint = testDataFile.getStartPoint();
finishPoint = testDataFile.getFinishPoint();
maxDuration = testDataFile.getMaxDuration();
randomGenerator = randomGen;
toRemoveRVI = 3;
//----------------(A) : Initialization----------------
parameterSet = new ParameterSet(neighbourhoodSize, testDataFile);
generateSComp(testDataFile, solution, S_Comp);
//---------Generating neighborhood solutions--------- //Generate number of neighborhood solutions (feasible and
//infeasible) to the current solution, based on current
//tabu parameters.
routeNumbers = twoRandomTours(solution, randomGenerator);
r1 = solution.get(routeNumbers[0]);
r2 = solution.get(routeNumbers[1]);
solution = insertInS(solution, routeNumbers, maxDuration, startPoint, finishPoint, S_Comp, SE, successfulInsert);
if(!successfulInsert)
{
solution = exchangeWithSComp(solution, parameterSet, routeNumbers, maxDuration, S_Comp, randomGenerator);
new RoutesToXLS(solution, "Tabu3");
}
else
{
new RoutesToXLS(solution, "Tabu2");
}
//----------------(B) : Improvement----------------
solution = balance(solution,r1,r2);
if(!successfulBalance)
{
exchangeBetweenTours(r1,r2);
new RoutesToXLS(solution, "Tabu5");
}
else
{
new RoutesToXLS(solution, "Tabu4");
}
if(q_tabu % parameterSet.getChi() == 0 && q_tabu!=0)
{
solution = RVI(solution, routeNumbers, maxDuration, startPoint, finishPoint, S_Comp, SE, randomGenerator, toRemoveRVI, successfulInsert);
new RoutesToXLS(solution,"AfterRVI");
}
}