java - Why all elements of my list seems to be the same? -


i have following code:

integer[] lastexchange = new integer[ncolors]; integer[] newexchange = new integer[ncolors]; while (true) {     ...     (int i=0; i<ncolors; i++) {        lastexchange[i] = newexchange[i];     }     ...     exchanges.add(lastexchange);     output.log.fine("exchange:" + lastexchange[0] + "," + lastexchange[1]); } (integer[] exchange : exchanges) {     output.log.fine("exchange:" + exchange[0] + "," + exchange[1]); } 

i have 2 outputs (one in while loop 1 in loop). first output shows me add different arrays list. while when double check in second loop see elements of exchange list same (they equal first element of list).

does know doing wrong here?

as unwind's answer states, you're adding reference same array in every iteration of loop. need create new array each time:

// it's not clear newexchange populated integer[] newexchange = new integer[ncolors]; while (true) {     integer[] lastexchange = new integer[ncolors];     ...     (int i=0; i<ncolors; i++) {        lastexchange[i] = newexchange[i];     }     ...     exchanges.add(lastexchange);     output.log.fine("exchange:" + lastexchange[0] + "," + lastexchange[1]); } 

alternatively, if you're cloning array:

integer[] newexchange = new integer[ncolors]; while (true) {     integer[] lastexchange = newexchange.clone();     ...     exchanges.add(lastexchange);     output.log.fine("exchange:" + lastexchange[0] + "," + lastexchange[1]); } 

Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -