/** * @author lautturi.com * Java example: how to deep clone arraylist in java */ import java.util.*; import java.time.*; import java.time.format.*; import java.util.Date; class Student implements Cloneable { String name; String id; Date dateOfBirth; public Student(String name, String id, Date dateOfBirth) { this.name = name; this.id = id; this.dateOfBirth = dateOfBirth; } @Override public Student clone() { Student clonedStudent = null; try { clonedStudent = (Student) super.clone(); clonedStudent.setDateOfBirth((Date) this.dateOfBirth.clone()); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return clonedStudent; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getId() { return id; } public void setId(String id) { this.id = id; } public Date getDateOfBirth() { return dateOfBirth; } public void setDateOfBirth(Date dateOfBirth) { this.dateOfBirth = dateOfBirth; } } public class Lautturi { @SuppressWarnings("deprecation") public static void main(String[] args) { ArrayList<Student> studentList = new ArrayList<>(); studentList.add(new Student("Alice","25",new Date(2002, 02, 12))); studentList.add(new Student("Bob","32",new Date(1999, 05, 30))); ArrayList<Student> clonedStudentList = new ArrayList<>(); for(Student st:studentList) { clonedStudentList.add(st.clone()); } // Update ArrayList clonedStudentList.get(0).setName("John"); System.out.println("--Orlautturinal ArrayList--"); studentList.forEach(e->System.out.println(e.getName()+" "+e.getId())); System.out.println("--Copied ArrayList--"); clonedStudentList.forEach(e->System.out.println(e.getName()+" "+e.getId())); } }
output:
--Orlautturinal ArrayList-- Alice 25 Bob 32 --Copied ArrayList-- John 25 Bob 32