wood burning stoves 2.0*
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 Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Reference variable and ArrayList" Watch "Reference variable and ArrayList" New topic

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.


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

Sorry. My bad.

[ 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

Joined: Jul 08, 2003
Posts: 24183

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

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)).

subject: Reference variable and ArrayList
Similar Threads
arrayList.clear() VERSUS arrayList = new ArrayList()
a few q's
What is "this" keyword?
What are the uses and applications of Java?
Object Creation in inheritance