I wrote a code to check if an array is not in a list, then it should add it to another list. I used a linked list for this. But my problem is the program always add multiple copies of the current array and remove what's inside in the list before: My code is as follows:

And this is the result I got after running:
current f is [0, 0]
content of the list New
[0, 0]
finished printing the list New
current f is [0, 1]
content of the list New
[0, 1]
[0, 1]
finished printing the list New
current f is [1, 0]
content of the list New
[1, 0]
[1, 0]
[1, 0]
finished printing the list New
current f is [1, 1]
content of the list New
[1, 1]
[1, 1]
[1, 1]
[1, 1]
finished printing the list New

Please help!!!!

November 30th, 2010, 09:20 AM

KevinWorkman

Re: Problem with adding to a list in a loop

When posting code, make sure you use the code tags to preserve highlighting. Otherwise nobody will want to read it.

November 30th, 2010, 10:13 AM

copeg

Re: Problem with adding to a list in a loop

As mentioned, for future reference please flank your code with the [highlight=java][/highlight] tags. For now I have edited your post to reflect this.

Your code changes the reference to the array, so any changes to said reference will be reflected in the references in the List. To add new values, you should create new references (eg place the int [] f = new int [2]; inside the double for loop). In general, its good practice to give variables meaningful names and don't even come close to conflicting with standard java statements (eg 'New').