我创建新的染色体并添加到列表中(我确定染色体是不同的,因为我在添加之前已经打印了它们(,但最终当我打印列表或获得随机索引时,只有最后两条染色体。通常在中间期间,我从当前一代的两条随机染色体中创建两条新染色体,以便通过交叉创建新一代(。
public Population crossoverChromosomes(Population population, List<Item> items, int capacityOfKnapsack) {
Random rand = new Random();
List<Chromosome> chromosomeList = new ArrayList<>(population.getChromosomeList());
int genesLength = population.chromosomeList.get(0).getGenes().length;
int newGenes1[] = new int[genesLength];
int newGenes2[] = new int[genesLength];
ArrayList<Chromosome> newCrossoverPopulation = new ArrayList<>();
for (int j = 0; j < population.getPopulationSize() / 2; j++) {
int firstChrIndex = rand.nextInt(population.getPopulationSize() - 1);
int secondChrIndex = rand.nextInt(population.getPopulationSize() - 1);
int d = rand.nextInt(population.getPopulationSize() - 1);
Chromosome firstChr = chromosomeList.get(firstChrIndex);
Chromosome secondChr = chromosomeList.get(secondChrIndex);
for (int i = 0; i < genesLength; i++) {
if (i < d) {
newGenes1[i] = firstChr.getGenes()[i];
newGenes2[i] = secondChr.getGenes()[i];
} else {
newGenes1[i] = secondChr.getGenes()[i];
newGenes2[i] = firstChr.getGenes()[i];
}
}
Chromosome chr1 = new Chromosome(genesLength, newGenes1);
Chromosome chr2 = new Chromosome(genesLength, newGenes2);
chr1.fitnessCalculate(items, capacityOfKnapsack);
newCrossoverPopulation.add(chr1);
chr2.fitnessCalculate(items, capacityOfKnapsack);
newCrossoverPopulation.add(chr2);
}
return new Population(newCrossoverPopulation.size(), newCrossoverPopulation);
}
我发现了问题,即使我在创建染色体时使用"new"运算符,chr1 和 chr2 并添加新染色体,最后每个引用仅引用 chr1 或 chr2,以便最后两个最新对象。为什么它不起作用?也许我应该以这种方式创建新的染色体 list.add(new chr(?编辑:它仍然不起作用我不知道为什么列表中的对象总是引用最后两个创建的染色体对象。 编辑2:已解决(我只在循环之前创建了表,即使我的对象是新的参考,染色体中的变量"基因"仍然是我在循环之前创建的相同表(