- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to copy or clone a Java ArrayList?
The clone() method of the java.util.ArrayList class returns a shallow copy of this ArrayList instance (i.e the elements themselves are not copied). Using this method, you can copy the contents of one array list to other.
Example
import java.util.ArrayList; public class ArrayListDemo { public static void main(String args[]) { ArrayList<StringBuilder> arrlist1 = new ArrayList<StringBuilder>(); arrlist1.add(new StringBuilder("Learning-")); ArrayList arrlist2 = (ArrayList) arrlist1.clone(); StringBuilder strbuilder = arrlist1.get(0); strbuilder.append("list1, list2-both pointing to the same StringBuilder"); System.out.println("The 1st list prints: "); for (int i = 0; i < arrlist1.size(); i++) { System.out.print(arrlist1.get(i) + " "); } System.out.println("The 2nd list prints the same i.e:"); for (int i = 0; i < arrlist2.size(); i++) { System.out.print(arrlist2.get(i)); } } }
Output
The 1st list prints: Learning-list1, list2 - both pointing to the same StringBuilder The 2nd list prints the same i.e: Learning-list1, list2 - both pointing to the same StringBuilder
- Related Articles
- How to copy or clone a C# list?
- How to clone or copy a list in Python?
- How to clone or copy a list in Kotlin?
- C# program to clone or copy a list
- Python program to clone or copy a list.
- Clone an ArrayList in Java
- How to copy elements of ArrayList to Java Vector
- Copy Elements of One ArrayList to Another ArrayList with Java Collections Class
- How to create a shallow copy of ArrayList in C#?
- How to Clone a List in Java?
- How to Clone a Map in Java
- Copy all elements of ArrayList to an Object Array in Java
- How to convert Java array or ArrayList to JsonArray using Gson in Java?
- How to copy the entire ArrayList to a one-dimensional Array in C# ?
- How to remove an element from ArrayList or, LinkedList in Java?

Advertisements