0

I'm working on a genetic algorithm, right now I'm stuck on populating, because two separate array instances of a link class seemingly keep effecting each other, and I can't figure out why.

here is the relevant code for my problem, let me know if you need more:

private ArrayList<Link> mNetwork = new ArrayList<Link>();
private ArrayList<Link> network = new ArrayList<Link>();

public GeneticAlgorithm(ArrayList<Link> network, int populationSize,
        int tournamentsSize, double crossoverProb, double mutationProb) {
    mNetwork = network;
    mPopulationSize = populationSize;
    mTournamentsSize = tournamentsSize;
    mCrossoverProb = crossoverProb;
    mMutationProb = mutationProb;

createInitialPopulation();

}

public void createInitialPopulation() {     
    for(int z = 0; z < mPopulationSize; z++){
        network = mNetwork;
        for(int i = 0; i < network.size(); i++){
           int linkRan = ran.nextInt(10);
            if(linkRan == 6){
                network.get(i).setActive(1);
                if(mNetwork.get(i).getActive() ==network.get(i).getActive(){
                    System.out.println("These Shouldn't match");
                }
}
                else{
                    network.get(i).setActive(0);

            }
}
}
}

The "These shouldn't match" prints out every time, and I don't know why, this is a problem, because I want to use the initial network as a way to reset the values when populating.

Also the Link class isn't set to static or anything like that, but if you want to see more of the code just ask, because I'm pretty sure this should be all that's necessary, but it could very well not be.

2 Trainz
  • 1
  • 1
  • 1
    `network = mNetwork;` sets them to reference the same list, so why shouldn't they match? – UnholySheep May 02 '17 at 00:15
  • Following unholy's comment, maybe your looking for network =(ArrayList) mnetwork .clone(); to duplicate the list. – Nick Ziebert May 02 '17 at 00:17
  • @NickZiebert cloning the ArrayList itself might not be enough; depending on what OP is after, it might be necessary to create a new array containing clones of the Link objects from the original array! – Kevin Anderson May 02 '17 at 00:31
  • @KevinAnderson You are right, hence the link to the duplicate – Scary Wombat May 02 '17 at 00:35
  • @UnholySheep so when I set one to equal the other, it keeps updating them together? It's different than say `someString = someOtherString` where it just sets them equal? – 2 Trainz May 02 '17 at 00:36
  • anyways, I never realized cloning an arrayList was more work than just setting it equal, although it makes sense, I've just never ran into it before. thanks for helping me. – 2 Trainz May 02 '17 at 00:44

0 Answers0