Question

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;
}
Was it helpful?

Solution

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);

OTHER TIPS

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top