I have this problem of object references which is driving me crazy. Is it normal that when I get an Integer[] array from an object and modify some elements in this variable, it gets modified in the object as well without using any set method? For example below I want to modify timetable variable locally but not in the bestSoFar object. How can I do this? and what is really happening here?
for (IntTuple examRel: examsRel)
{
int[] examsTogether = examRel.getData();
double maxFitness = 0.0;
Integer[] timetable = bestSoFar.getChromosome();
for (int i=0; i < noOfTimeslots; i++)
{
for (int j=0; j < examsTogether.length; j++)
{
timetable[examsTogether[j]] = i;
}
BestChromosome thisChromosome = evaluateChromosome(new BestChromosome(timetable));
double thisFitness = thisChromosome.getFitness();
if (thisFitness > maxFitness)
{
maxFitness = thisFitness;
bestSoFar = thisChromosome;
}
}
}
return bestSoFar;
}
getChromosome()is returning a reference to the underlying storage, rather than creating a copy first.Integer[]array. If you need other behavior, you should consider cloning array before returning it.