当我尝试应用GA算法时,我发现了一个问题:我将列表A的值复制到另一个B,然后我操纵了B.但是当我运行单元测试时。我只是发现A和B的值都发生了变化。我不知道发生了什么。 以下是我的代码:
public class GA_bags {
private Population population;
private int fittest;
private List<Individual> offsprings;
public GA_bags(int n,int sumBags,int maxWeight,Bag[] bags){
this.population=new Population(n,sumBags,maxWeight,bags);
}
//Crossover Function
public void crossover(){
Random random=new Random();
List<Individual> individuals=population.getIndividuals();
offsprings=new ArrayList<>(individuals); //Intialize the offsprings, simply copy first
int pos=random.nextInt(offsprings.get(0).getGenes().length); //decide the position of genes to crossover
for(int i=0;i<offsprings.size()-1;i+=2){ //1st fittest pair with 2nd fittest,3nd with the 4th...
for(int j=0;j<=pos;j++){
int tem=offsprings.get(i).getGenes()[j];
offsprings.get(i).getGenes()[j]=offsprings.get(i+1).getGenes()[j];
offsprings.get(i+1).getGenes()[j]=tem;
}
}
}
实现交叉方法后,List个体和后代都发生了变化,但我只是操纵了List offsprings。
public class Individual {
//each individual is a solution of KnapsackProblem
private int[] genes; //"1" stands for the bag is chosen, while "0" stands for the bag is not
private Bag[] bags; //each digit of gene is responsible for a specific Bag object
private int fitness; //the fitness of an individual
private int curWeight; //the weight of this individual
private int maxWeight; //once the total weight of bags of this individual over maxWeight, then fitness is 0
public Individual(int sumBags,int maxWeight,Bag[] bags){
this.genes=new int[sumBags];
this.maxWeight=maxWeight;
this.bags=bags;
Random random=new Random();
for(int i=0;i<sumBags;i++){
genes[i]=random.nextInt(2); //genetic code: random generate genes,"0" or "1"
}
}
}
答案 0 :(得分:2)
关于深层复制,here就是一个例子。
如果要复制基元类型,可以使用=
。如果要复制对象,=
只是使变量指向对象地址。所以这两个变量都指向同一个对象。
如果您想要新的变量指向一个全新的对象,您需要自己复制它。最简单的方法是逐个复制原始属性。