# Reference variable and ArrayList

Andre Brito
Ranch Hand
Posts: 95
Hi everyone. I'm sorry the dumb question, but I don't know why this is happening.

I have the following code:

Ok. It works, but I'm trying to create a List of FuncaoDePertinencia like this:
a = 1, b = 1, c = 1, d = 1
a = 2, b = 2, c = 2, d = 2

But it comes like this:
a = 2, b = 2, c = 2, d = 2
a = 2, b = 2, c = 2, d = 2

I believe that that happens because the reference variable chages and the List changes everything that has the same name of the reference variable. Am I right? Or completely wrong?

Now, I'm solving this problem creating a differente reference variable for each FuncaoDePertinencia object that I'm adding in the ArrayList. So, if I'll have 100 FuncaoDePertinencia object, I'll have 100 diferent variables (named f1, f2, ..., f100).

What's the real good way non-foolish-correct-and-elegant to solve this?

Cumps from Brazil.
I'm sorry my english. It's not very good.

Hugs.
Andre.

Oooopz. Now I figure it out that I could write something like this:

Sorry. My bad.
[/edit]

[ November 02, 2008: Message edited by: Andre Brito ]

[ November 02, 2008: Message edited by: Andre Brito ]
[ November 02, 2008: Message edited by: Andre Brito ]

Ernest Friedman-Hill
author and iconoclast
Marshal
Posts: 24212
35
If the code you're using is really exactly as you've shown, then this shouldn't happen. But if that second "array = new int[4]" is not actually there, then indeed, you'd see the problem you describe. I suspect that you're actually just reusing that array, rather then creating a new one each time as you've shown here.

Andre Brito
Ranch Hand
Posts: 95
Ernest,
Thank you for the answer

Actually I was using the exactly same code that I wrote.
After changing the parameters to add(new ...), I fixed the problem in a better way.

But now that you said, I've another doubt: even for primitive type that happens? I thought it was just for reference variables (like Objects)).

Thanks.