How to Copy Elements of One ArrayList to Another in Java


In this example we will show how to copy all elements of one ArrayList object to another ArrayList Object with toArray method in Java.

Source Code

package com.beginner.examples;

import java.util.ArrayList;

public class ArraylistToObjectArray {

	public static void main(String[] args) {

		ArrayList nameList = new ArrayList();

		// Add elements
		nameList.add("Tom");
		nameList.add("Jack");
		nameList.add("John");

		// Convert to an array of objects
		Object[] names = nameList.toArray();

		for (int i = 0; i < names.length; i++) {
			
			System.out.println(names[i]);
		}

	}

}

Output:

Tom
Jack
John

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments