Sarah
Sarah

Reputation: 11

Class instance change another instance

The code is :

package classes;

public class Test {
    private static double mutationRate = 0.5;

    public static void main(String[] args) {
        Population pop = new Population();
        pop.initialise();
        Population po = new Population();
        po.getIndividusList().add(pop.getFittest());
        po.getIndividusList().add(mutate(pop.getIndividusList().get(1)));
    }

    private static Chromosom mutate(Chromosom l) { // changer les couples d'interventions des parcs)
        // loop through genes
        Chromosom ch = new Chromosom();
        for (int i = 0; i < l.size(); i++)
            ch.put(i, l.get(i));

        for (int i = 0; i < ch.size(); i++) {
            double alea = Math.random() * 13;
            int moisIntervention1 = (int) alea;

            Intervention interv1 = new Intervention(1, moisIntervention1);
            ch.get(i).modInterventions(ch.get(i).intervention2(interv1));
        }
        return ch;
    }
}

The problem is that I did not change the instance pop but when I change the other instance po, pop changes too.

Upvotes: 0

Views: 202

Answers (2)

Diego Martinoia
Diego Martinoia

Reputation: 4652

I'm unsure about whether I understood the problem, but I think that you mean that when you alter the items in Population po, the items in Population pop mirror those changes.

That is, indeed, the expected behavior of your code: to populate po, you are adding items from pop - (pop.getFittest, pop.getList.get(1) ).

But the individuals are, I believe, instances of objects, so add/remove and similar operations work with references to the objects, and not with copies of them. Therefore, as you have 2 references to the same obj, any change is mirrored.

IF you want to create a copy, you should add to po a new object with the same state, either by creating a constructor that takes another instance as parameter, implementing a copy method, or something similar.

It should be something like this:

    Population po = new Population();
    Individual fittest = pop.getFittest();
    Individual poCopy = new Individual();
    //ADD CODE HERE TO COPY ALL THE FIELDS FROM fittest TO poCopy
    //....

    po.getIndividusList().add(poCopy);

Upvotes: 0

Sanjay Rabari
Sanjay Rabari

Reputation: 2081

java pass by value.

when you call this mutate(pop.getIndividusList().get(1))

you are sending pop's instance, so it will get change.

Supose pop.getIndividusList().get(1) return String varibale do this way

String var=pop.getIndividusList().get(1);

then call mutate(var)

Upvotes: 1

Related Questions