Hi, I basically have 1 arrayList with 10 elements.

//arraylist with10 elements
private ArrayList<String> arrayList1 = new ArrayList<String>();
//arraylist with nothing in it.
private ArrayList<String> arrayList2 = new ArrayList<String>();


public void copy() {

Collections.copy(arrayList1, arrayList2);
	    
}

//The code above will copy all the elements in the first arraylist to the 2nd arraylist.

However the thing is....I need to copy many arraylists, if the user wants 5 arraylists I will have to create 5 arraylists and put all the arrayList1 elements in them. I don't know how to do this. Can any1 help me?

for(int i=0; i<5;i++){

//create new ArrayList each time
// copy all the elements from ArrayList1 to new ArrayList
}

I know the theory for it but dont know how to implement it. Can any1 help me? I have spent more than 2 hours on this.

Try to first copy one ArrayList to a new one.

  1. Create a new ArrayList.
  2. Iterate over all the cells of the original ArrayList
  3. Add each cell from the original ArrayList to the new one.

After you have copied the entire original ArrayList to a new one, try to think how to expand the solution to all ArrayList. If you are having trouble, post the code you have so far.

Edited 6 Years Ago by apines: n/a

If you need to create a variable number of ArrayLists then you will need some kind of container to put them in, eg an array or ArrayLists or an ArrayList of ArrayLists.
Start with an new empty container, then in your loop create copies of the original ArrayList and add those copies to the container.

Actually you can just use the System class' arraycopy method, which is designed specifically for this purpose. Check it out in the java api -- the documentation for the arraycopy method is pretty straightforward but if you have any questions with it don't be afraid to ask :)

Iterating over the arraylist works as well, but arraycopy is faster and simpler.

Yup, arraycopy copies arrays not ArrayLists. Collections.copy is the one.
On the other hand, there is a constructor for ArrayList that does the same thing even more easily by taking any Collection as parameter and initialising the new ArrayList with all the data from that Collection, eg

ArrayList myCopyList = new ArrayList(myOriginalList);

Edited 6 Years Ago by JamesCherrill: n/a

This article has been dead for over six months. Start a new discussion instead.