I have a problem with getting a new value of an object. I have a code like that:
...
TimeSchedule[] offspringScheduleOne = new TimeSchedule[AVAILABLE_CLASSROOMS];
...
offspringScheduleOne[i] = genes.get(geneOneIndex).getSchedule()[i];
...
After that assignment offspringScheduleOne[i] and genes.get(geneOneIndex).getSchedule()[i] points the same memory address. I want that: offspringScheduleOne[i] should get the value of the genes.get(geneOneIndex).getSchedule()[i], they musn’t be same, they just should have same values.
TimeSchedule class:
public class TimeSchedule extends AlgorithmParameters {
public int[][] timetable = new int[DAYS][HOURS];//DAYS and HOURS are static final variables that comes from AlgorithmParameters
public int[][] getTimetable() {
return timetable;
}
public void setTimetable(int[][] timetable) {
this.timetable = timetable;
}
}
How can I do that?
It actually is copying the value – but you need to understand what that value is.
The value of
offspringScheduleOne[0]isn’t aTimeScheduleobject. It’s a reference to aTimeScheduleobject. No expression in Java has a value which is an object. It’s really important that you understand this.Now, if you want a copy of the object, you’ll have to make that happen yourself. For example, you could include a
clone()method inTimeSchedule, and write:In other words, create a clone of the existing object, and then set
offspringScheduleOne[i]to be a reference to that newly created object. Of course, if any of the fields withinTimeScheduleis a reference type field, you’ll need to consider whether or not you need to clone that object as well…… or you could add a constructor and call that, or another method, etc. But you need to be absolutely clear that the assignment operator is copying the value, but that value is a reference.
EDIT: Okay, now that you’ve posted
TimeSchedule, a few suggestions:Rather than having properties returning the whole array, change them to access an individual hour, e.g.
Create a clone method like this:
(That’s slightly wasteful in that it will create the subarrays and then discard them, but let’s get something which works first…)
}
public Test clone() {
int[][] timetableCopy = new int[timetable.length][];
for (int i = 0; i < timetable.length; i++) {
timetableCopy[i] = timetable[i].clone();
}
return null;
}