Reputation: 2592
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;
}
Upvotes: 1
Views: 81
Reputation: 692271
Yes, it's normal. The method is returning a reference to the array that is contained in your object. If you change what the array contains, the array is thus modified.
You'll have to make a defensive copy of the array before returning it.
You could avoid these copies by using a List<Integer>
instead, and return an unmodifiable view of this list to prevent its modification. It would then be up to the caller to create a copy of the list if it needs to modify it:
return Collections.unmodifiableList(list);
Upvotes: 1
Reputation: 312354
An array in Java is an Object, so when you modify its elements, they change for all the references pointing to that array. If you want a local copy, you should clone it. E.g.:
Integer[] origTimetable = bestSoFar.getChromosome();
Integer[] timetable = Arrays.copyOf (origTimetable, origTimeable.length);
Upvotes: 5