java - Array gets overwritten for no apparent reason -
problem
have written loop in fill array sum objects. works fine, loop gets next iteration overwrites first index of array.
what have tried
tried see if maybe problem resides in different piece of code (such sum class). not find disturb loop.
tried find other variables same name (even in other methods, since desperate) , see if maybe changed iterator somewhere else. couldn't find related that.
tried looking around on internet , find related accidentally overwriting arrays couldn't find either.
code
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 = 0; < 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; } }
expectations
i'm expecting output of 1 + 1 , 2 - 1. getting following: 2 - 1 , 2 - 1 when i'm done.
if spots i'm doing wrong or see more information or code on side please so. in advance.
i'm going assume sum
class doesn't store sum, instead computes array constructed whenever it's needed.
it looks sum
objects share same array -- you're passing same reference every time construct sum
. furthermore, every time loop on j
overwrite contents of array.
so when done, sums same.
you should able around giving each sum
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 = 0; < 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; } }
Comments
Post a Comment