- Java ArrayList clone()
- clone() Parameters
- clone() Return Value
- Example 1: Make a Copy of ArrayList
- Example 2: Print the Return Value of clone()
- Java ArrayList clone() and Deep Copy Example
- Клонировать список в Java
- 1. Использование конструктора копирования
- 2. Использование addAll(Collection c) метод
- 3. Использование Java 8
- 4. Использование Object.clone() метод
- 5. Использование Apache Commons Lang
- How to Deep Copy Arraylist in Java
- Example of Deep Copy ArrayList
- Deep Copy using Clone() Method
- Complete code to deep copy ArrayList in java
- Was this post helpful?
- You may also like:
- Update Value of Key in HashMap in Java
- Create Array of Linked Lists in Java
- Return ArrayList in Java
- Create List with One Element in Java
- How to Add Multiple Values for Single Key In HashMap in Java
- [Fixed] java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList
- Create ArrayList of Objects in Java
- How to remove element from Arraylist in java while iterating
- Print HashMap in Java
- Print LinkedList in java
- Share this
- Related Posts
- Author
- Related Posts
- Update Value of Key in HashMap in Java
- Create Array of Linked Lists in Java
- Return ArrayList in Java
- Create List with One Element in Java
- How to Add Multiple Values for Single Key In HashMap in Java
- [Fixed] java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList
Java ArrayList clone()
Here, the shallow copy means it creates copy of arraylist object. To learn more on shallow copy, visit Java Shallow Copy.
The syntax of the clone() method is:
Here, arraylist is an object of the ArrayList class.
clone() Parameters
The clone() method does not have any parameters.
clone() Return Value
Example 1: Make a Copy of ArrayList
import java.util.ArrayList; class Main < public static void main(String[] args)< // create an arraylist ArrayListnumber = new ArrayList<>(); number.add(1); number.add(3); number.add(5); System.out.println("ArrayList: " + number); // create copy of number ArrayList cloneNumber = (ArrayList)number.clone(); System.out.println("Cloned ArrayList: " + cloneNumber); > >
ArrayList: [1, 3, 5] Cloned ArrayList: [1, 3, 5]
In the above example, we have created an arraylist named number . Notice the expression,
- number.clone() — returns a copy of the object number
- (ArrayList) — converts value returned by clone() into an arraylist of Integer type (To learn more, visit Java Typecasting)
Example 2: Print the Return Value of clone()
import java.util.ArrayList; class Main < public static void main(String[] args)< // create an arraylist ArrayListprime = new ArrayList<>(); prime.add(2); prime.add(3); prime.add(5); System.out.println("Prime Number: " + prime); // print the return value of clone() System.out.println("Return value of clone(): " + prime.clone()); > >
Prime Number: [2, 3, 5] Return value of clone(): [2, 3, 5]
In the above example, we have created an arraylist named prime . Here, we have printed the value returned by clone() .
Note: The clone() method is not specific to the ArrayList class. Any class that implements the Clonable interface can use the clone() method.
Java ArrayList clone() and Deep Copy Example
In Java, the ArrayList clone() method creates a shallow copy of the list in which only object references are copied. If we change the object state of a list item inside the first ArrayList, the changed object state will also be reflected in the cloned list.
To prevent changes reflected in both lists, we should explicitly create a deep copy of the list.
1. Using ArrayList.clone() for Shallow Copy
The clone() method creates a new ArrayList and then copies the backing array to cloned array. It creates a shallow copy of the given arraylist. In a shallow copy, the original list and the cloned list, both refer to the same objects in the memory.
Let us see the internal implementation of the clone method.
public Object clone() < try < ArrayListv = (ArrayList) super.clone(); v.elementData = Arrays.copyOf(elementData, size); v.modCount = 0; return v; > catch (CloneNotSupportedException e) < // this shouldn't happen, since we are Cloneable throw new InternalError(e); >>
The following Java program creates a shallow copy of an arraylist using clone() method.
ArrayList arrayListObject = new ArrayList<>(List.of("A", "B", "C", "D")); ArrayList arrayListClone = (ArrayList) arrayListObject.clone();
2. Creating a Deep Copy of ArrayList
Creating a deep copy of a list is not straightforward. Java does not support deep copying by default. So we have to manually modify the code to enable the deep copying of classes and collections. In a deep copy of the list, the items referred from both lists are different instances in the memory.
3.1. Enable Deep Copying on List Item
To create a deep copy of any class, divide all the class members into two categories of mutable and immutable types.
- All immutable field members can be used as it is. They don’t require any special treatment. e.g. primitive classes, wrapper classes and String class.
- For all mutable field members, we must create a new object of member and assign its value to cloned object.
The idea is to return an immutable copy of the class from clone() method. Checkout the overridden clone() method in the following class:
public class Employee implements Cloneable < private Long id; private String name; private Date dob; //Mutable field public Employee(Long id, String name, Date dob) < super(); this.id = id; this.name = name; this.dob = dob; >//Getters and setters @Override protected Object clone() throws CloneNotSupportedException < Employee clone = null; try < clone = (Employee) super.clone(); //Copy new date object to cloned method clone.setDob((Date) this.getDob().clone()); >catch (CloneNotSupportedException e) < throw new RuntimeException(e); >return clone; > @Override public String toString() < return "Employee [id=" + id + ", name=" + name + ", dob=" + dob + "]"; >>
3.2. Deep Copying a Java Collections
Creating a deep copy of a collection is rather easy. We need to create a new instance of collection and copy all elements from the given collection into the cloned collection – one by one. Note that we will copy the element’s clone in the cloned collection.
ArrayList employeeList = new ArrayList<>(); ArrayList employeeListClone = new ArrayList<>(); Collections.copy(employeeList, employeeListClone);
Java program to create a deep copy of an arraylist.
ArrayList employeeList = new ArrayList<>(); employeeList.add(new Employee(1l, "adam", new Date(1982, 02, 12))); ArrayList employeeListClone = new ArrayList<>(); Collections.copy(employeeList, employeeListClone); //Modify the list item in cloned list - it should affect the original list item employeeListClone.get(0).setId(2l); employeeListClone.get(0).setName("brian"); employeeListClone.get(0).getDob().setDate(13);; System.out.println(employeeList); System.out.println(employeeListClone);
Program output. Notice that even after changing the values of Employee object in employeeListClone , original employee list employeeList is not changed.
[Employee [id=1, name=adam, dob=Sun Mar 12 00:00:00 IST 3882]] [Employee [id=2, name=brian, dob=Mon Mar 13 00:00:00 IST 3882]]
Клонировать список в Java
В этом посте мы обсудим, как клонировать список в Java. Нам нужно построить список, содержащий указанные элементы списка в том же порядке, что и исходный список.
Предположим, что в списке нет изменяемых объектов, т. е. код может выполнять мелкая копия.
1. Использование конструктора копирования
Мы можем использовать конструктор копирования для клонирования списка, который представляет собой специальный конструктор для создания нового объекта как копии существующего объекта.
2. Использование addAll(Collection c) метод
List интерфейс имеет addAll() метод, который добавляет все элементы указанной коллекции в конец списка. Мы можем использовать то же самое для копирования элементов из исходного списка в пустой список.
3. Использование Java 8
Мы также можем использовать потоки в Java 8 и выше для клонирования списка, как показано ниже:
4. Использование Object.clone() метод
Java Object класс обеспечивает clone() метод, который можно переопределить, реализуя Cloneable интерфейс. Идея состоит в том, чтобы пройтись по списку, клонировать каждый элемент и добавить его в клонированный список. Мы также можем использовать Java 8 Stream, чтобы сделать то же самое.
5. Использование Apache Commons Lang
Несколько сторонних библиотек предоставляют удобные классы для Сериализация и десериализация объектов. Один из таких классов SerializationUtils предоставленный Apache Commons Lang, который serialize() а также deserialize() методы сериализации/десериализации объекта. Сериализованный объект не содержит ссылки на исходный объект при десериализации.
SerializationUtils также обеспечивает clone() метод, который показан ниже:
How to Deep Copy Arraylist in Java
When an object gets copied via reference not actual values then it is called Shallow copy . In it, changes made to an object will also reflect to another object. It means if we change elements of one object then the other object will also be changed.
In deep copy , the copied object is completely independent and changes made to it do not reflect to the original object.
Let’s understand with the examples.
Example of Deep Copy ArrayList
Here, we are copying one ArrayList elements to ther using addAll() method and see changes made to second list does not modify original list.
Note: This method will only work if ArrayList contains primitive data types or immutable collection. In case, ArrayList contains custom objects, then we need to explicitly clone the custom objects.
Deep Copy using Clone() Method
We can also use clone() method to create a copy of ArrayList but this method create swallow copy.
Let’s see with the help of example.
Create main class named CloneArrayListMain.java
clonedStudentList . forEach ( e — > System . out . println ( e . getName ( ) + » » + e . getId ( ) ) ) ;
As you can see, changes to clonedStudentList also got reflected in studentList .
To create a true deep copy of ArrayList, we should create a new ArrayList and copy all the cloned elements to new ArrayList one by one and we should also clone Student object properly.
To create deep copy of Student class, we can divide its class members to mutable and immutable types.
- Immutable fields( String data types): We can directly use immutable fields in cloned object. Immutable fields include wrapper classes, String and primitive types.
- Mutable fields( Date data type): We should create new object for the mutable attribute and then assign it to cloned object.
Here is the correct clone method for Student class.
As you can see, we have used super.clone() to clone the Student object and then set dateOfBirth explicitly to clonedStudent as Date is mutable field.
Here is code to create deep copy of ArrayList by copying cloned elements one by one to new ArrayList.
Complete code to deep copy ArrayList in java
Here is complete java program to create deep copy of ArrayList in java.
clonedStudentList . forEach ( e — > System . out . println ( e . getName ( ) + » » + e . getId ( ) ) ) ;
As you can see, changes made to clonedStudentList did not reflect in original ArrayList studentList .
That’s all about how to deep copy ArrayList in java.
Was this post helpful?
You may also like:
Update Value of Key in HashMap in Java
Create Array of Linked Lists in Java
Return ArrayList in Java
Create List with One Element in Java
How to Add Multiple Values for Single Key In HashMap in Java
[Fixed] java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList
Create ArrayList of Objects in Java
How to remove element from Arraylist in java while iterating
Print HashMap in Java
Print LinkedList in java
Share this
Related Posts
Author
Related Posts
Update Value of Key in HashMap in Java
Table of ContentsUsing the put() Method of HashMap Collection in JavaUsing the compute() Method of HashMap Collection in JavaUsing the merge() Method of the HashMap Collection in JavaUsing the computeIfPresent() Method of The HashMap Collection in JavaUsing the replace() Method of The HashMap Collection in JavaUsing the TObjectIntHashMap Class of Gnu.Trove Package in JavaUsing the […]
Create Array of Linked Lists in Java
Table of ContentsIntroductionLinked List in JavaApplication of Array of Linked ListsCreate Array of Linked Lists in JavaUsing Object[] array of Linked Lists in JavaUsing the Linked List array in JavaUsing the ArrayList of Linked Lists in JavaUsing the Apache Commons Collections Package Introduction In this article, we will look at how to Create an Array […]
Return ArrayList in Java
Table of ContentsReturn ArrayList in Java From a Static MethodReturn ArrayList in Java From a Non-static MethodConclusion This article discusses cases of returning an ArrayList in Java from a method. An ArrayList in Java is a collection of elements of the same data type under a single variable name. In different cases, you can return […]
Create List with One Element in Java
Table of ContentsUsing Collections.singletonList()Using Array.asList() method [ Immuatable list]Using new ArrayList with Array.asList() method [ Mutable list] In this post, we will see how to create List with One Element in java.. Using Collections.singletonList() This is best way to create List with single element if you need an immutable List. [crayon-64b80f2328ceb556428141/] Output [crayon-64b80f2328cef058356669/] If you […]
How to Add Multiple Values for Single Key In HashMap in Java
Table of ContentsHashMapCan HashMap Store Multiple Values AutomaticallyWays to Add Multiple Values for Single Key In HashMap in JavaUsing the Standard LibraryUsing Apache Commons LibraryUsing Google Guava LibraryUsing TreeSet as ValuesUsing a Wrapper ClassUsing Java TuplesUsing compute() Function in JDK 8Conclusion This article discusses the HashMap in Java and how to add multiple values for […]
[Fixed] java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList
Table of ContentsReason for java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayListFixes for java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayListUse ArrayList’s constructorAssign Arrays.asList() to List reference rather than ArrayList In this post, we will see how to fix java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList. ClassCastException is runtime exception which indicate that code has tried to […]