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

I have the following code:

Integer[] lastExchange = new Integer[nColors];
Integer[] newExchange = new Integer[nColors];
while (true) {
    ...
    for (int i=0; i<nColors; i++) {
       lastExchange[i] = newExchange[i];
    }
    ...
    exchanges.add(lastExchange);
    output.log.fine("Exchange:" + lastExchange[0] + "," + lastExchange[1]);
}
for (Integer[] exchange : exchanges) {
    output.log.fine("Exchange:" + exchange[0] + "," + exchange[1]);
}

I have two outputs (one in the while loop another one in the for loop). The first output shows me that I do add different arrays to the list. While when i do a double check in the second loop I see that all elements of the exchange list are the same (they are equal to the first element of the list).

Does anybody know what I am doing wrong here?

Answers


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

// It's not clear where newExchange is actually populated
Integer[] newExchange = new Integer[nColors];
while (true) {
    Integer[] lastExchange = new Integer[nColors];
    ...
    for (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 just cloning the array:

Integer[] newExchange = new Integer[nColors];
while (true) {
    Integer[] lastExchange = newExchange.clone();
    ...
    exchanges.add(lastExchange);
    output.log.fine("Exchange:" + lastExchange[0] + "," + lastExchange[1]);
}

Need Your Help

Why is my program asking for permission to run on Vista?

visual-studio-2008 windows-vista

I've just built a VS C++ 6.0 program using VS 2008. When I attempt to run or debug the application, Vista asks for permission. What is it about how the program is built that causes this? The pro...

django authenticate not working

python django authentication

I was working with a legacy database where there was a table 'tbl_personaldetails', from where i ported data to custome user model.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.