We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › ArrayList problem
Page Index Toggle Pages: 1
ArrayList problem (Read 649 times)
ArrayList problem
Dec 28th, 2009, 3:16pm
 
Hello i have a problem with an ArrayList variables.
Here is function, aList is an arraylist variable with size=10:

Code:

void generate(ArrayList aList) {
ArrayList tmp = aList;

for(int i=0; i<2; i++) { // #1 loop
for(int j=0; j<10; j++) { // #2 loop
int index = int(random(tmp.size()));
Obj o = (Obj) tmp.get(index); // get element with random index

//some instructions

tmp.remove(index); // remove element from arraylist
}
// this loop clears tmp arraylist
// so i want to start next iteration with previous content of tmp arraylist before removing elements.


tmp = aList; // restoring previous content.
}


}


When the #2 loop ends aList size is 0
Why aList variable do not contain any elements ?
Thatat's why tmp = aList make no sens
Help...
Re: ArrayList problem
Reply #1 - Dec 28th, 2009, 4:14pm
 
IIRC when you do tmp=alist you just create a reference to the array, not a true copy. So when you empty tmp you also empty alist. This is something of a FAQ.  i.e. search if you want more detail Wink
Re: ArrayList problem
Reply #2 - Dec 29th, 2009, 2:13am
 
You can do instead:
Code:
ArrayList tmp = new ArrayList(aList); 


It should copy the content of the list, so you can alter tmp without changing aList.

...
Checking...
Code:
ArrayList al = new ArrayList();
al.add("Foo");
al.add("Bar");
ArrayList nal = new ArrayList(al);
nal.add("Buz");
nal.remove(1);
for (int i = 0; i < al.size(); i++) print(al.get(i) + " "); println();
for (int i = 0; i < nal.size(); i++) print(nal.get(i) + " "); println();
Page Index Toggle Pages: 1