【问题标题】:List contain only two last objects when I try add different objects当我尝试添加不同的对象时,列表仅包含最后两个对象
【发布时间】:2018-10-29 08:00:48
【问题描述】:

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

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

【问题讨论】:

  • 你尝试调试了吗?

标签: java list object arraylist genetic-algorithm


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    • 2013-06-07
    • 2020-01-18
    • 1970-01-01
    相关资源
    最近更新 更多