public Task(Object[] parameters) { this.number_of_sums = Integer.parseInt((String)parameters[0]); this.variables_per_sum = Integer.parseInt((String)parameters[1]); this.sum_parameters = new Object[this.variables_per_sum]; this.sums = new Sum[this.number_of_sums]; int z = 0; for(int i = 0; i < this.number_of_sums; i++) { int x = 0; for(int j = (2 + z); j < ((this.variables_per_sum + 2) + z); j++) { this.sum_parameters[x] = parameters[j]; x++; } this.sums[i] = new Sum(this.sum_parameters); System.out.println("Index 0: "+sums[0]); //1st iteration: 1 + 1 //2nd iteration: 2 - 1 System.out.println("Index 1: "+sums[1]); //1st iteration: null //2nd iteration: 2 - 1 z += this.variables_per_sum; } }
If anyone spots anything I'm doing wrong or would like to see more information or code on my side please say so. Thanks in advance.
I'm going to assume the Sum
class doesn't store its sum, but instead computes it from the array it was constructed with whenever it's needed.
It looks like all the Sum
objects will share the same array -- you're passing the same reference every time you construct a Sum
. Furthermore, every time you loop over j
you overwrite the contents of that array.
So when everything is done, all the sums are the same.
You should be able to get around this by giving each Sum
a different sum_parameters
:
public Task(Object[] parameters)
{
this.number_of_sums = Integer.parseInt((String)parameters[0]);
this.variables_per_sum = Integer.parseInt((String)parameters[1]);
this.sums = new Sum[this.number_of_sums];
int z = 0;
for(int i = 0; i < this.number_of_sums; i++)
{
Object[] sum_parameters = new Object[this.variables_per_sum];
int x = 0;
for(int j = (2 + z); j < ((this.variables_per_sum + 2) + z); j++)
{
sum_parameters[x] = parameters[j];
x++;
}
this.sums[i] = new Sum(sum_parameters);
System.out.println("Index 0: "+sums[0]); //1st iteration: 1 + 1 //2nd iteration: 2 - 1
System.out.println("Index 1: "+sums[1]); //1st iteration: null //2nd iteration: 2 - 1
z += this.variables_per_sum;
}
}
Each one of your Sum
objects is constructed with this.sum_parameters
as a parameter:
this.sums[i] = new Sum(this.sum_parameters);
When sum_parameters
is modified in each iteration of the outer loop, it changes internally in the objects constructed around references to it .
You should make an internal copy of sum_parameters
in each Sum
object.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.