Hi Folks, I’m new to this coding lark as well as Processing so I’m sure this is just me being dumb but I can’t figure it. I have created a small subset of my code to more easily explain it.
ArrayList<trainData> td;
void setup () {
td = new ArrayList<trainData>(2);
float[] in = new float[2];
in[0] = 1.0;
in[1] = 1.0;
td.add( new trainData(in));
// in = new float[2];
in[0] = 2;
in[1] = 3;
td.add( new trainData(in));
for (trainData d : td) {
println(d.Testinputs);
}
}
class trainData {
float[] Testinputs;
trainData(float[] i_) {
Testinputs = i_;
}
}
If I run the code as above I get {2,3} in both entries in my ArrayList. If I remove the comment “// in = new float[2];” and rerun it I get {1,1} in the first entry in the Array List and {2,3} in the second. This is what I expected to get from the first run.
When I debug it with the comment in as soon as it runs “in[0] = 2;” it updates the Testinputs in the first entry.
I would have thought the first entry in the ArrayList should safe and sound in the ArrayList by the time this line executes.
I can clearly work around the problem but what am I missing.
Processing / Java object references are basically pointers. You pass in this reference to trainData and assign it to Testinput but they are all referring to the same actual array. Unless you copy the array (eg. i_.clone()) or create one using new every reference is to the same array, and so if you change the values through one reference you change the values everywhere that array is referenced.
Incidentally, it is conventional to name classes starting uppercase, and fields starting lowercase - eg. TrainData and testInputs.