当我尝试添加不同的对象时,List仅包含两个最后的对象

时间:2018-05-18 20:22:22

标签: java list object arraylist genetic-algorithm

我创建新的染色体并添加到列表中(我确定染色体是不同的,因为我在添加之前已经打印过它们)但最后当我打印列表或得到随机索引时,只有两个最后(通常在交互过程中,我会从当前一代的两条随机染色体中创建两条新染色体,以便通过交叉创造新一代)。

 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);
    }

1 个答案:

答案 0 :(得分:0)

我发现问题,即使我在创建染色体,chr1和chr2期间使用“new”操作符并添加新的染色体,最后每个引用仅引用chr1或chr2,以便持续两个最新的对象。为什么它不起作用?也许我应该用这种方式创建新的染色体list.add(new chr)?编辑:它仍然无法工作我不知道为什么列表中的对象总是引用最后两个创建的染色体对象。 EDIT2:已解决(我在循环之前创建了表格,即使我的对象是一个新的参考,染色体中的变量“基因”仍然是我在循环之前创建的表)