This week's book giveaway is in the OCPJP forum.
We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Reference variable and ArrayList Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Reference variable and ArrayList" Watch "Reference variable and ArrayList" New topic
Author

Reference variable and ArrayList

Andre Brito
Ranch Hand

Joined: Dec 13, 2007
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.


[edit]
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

Joined: Jul 08, 2003
Posts: 24187
    
  34

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.


[Jess in Action][AskingGoodQuestions]
Andre Brito
Ranch Hand

Joined: Dec 13, 2007
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Reference variable and ArrayList