How do you make a shallow copy of a list in Java?


We can create a shallow copy of a list easily using addAll() method of List interface.

Syntax

boolean addAll(Collection>? extends E> c)

Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator.

Type Parameter

  • E − The runtime type of the collection passed.

Parameters

  • c − Collection containing elements to be added to this list.

Returns

True if this list changed as a result of the call

Throws

  • UnsupportedOperationException − If the addAll operation is not supported by this list.

  • ClassCastException − If the class of an element of the specified collection prevents it from being added to this list.

  • NullPointerException − If the specified collection contains one or more null elements and this list does not permit null elements, or if the specified collection is null.

  • IllegalArgumentException − If some property of an element of the specified collection prevents it from being added to this list.

Example

The following example shows how to create a shallow copy of a list using addAll() method.

package com.tutorialspoint;

import java.util.ArrayList;
import java.util.List;

public class CollectionsDemo {
   public static void main(String[] args) {
      List<Student> list = new ArrayList<>();
      list.add(new Student(1, "Zara"));
      list.add(new Student(2, "Mahnaz"));
      list.add(new Student(3, "Ayan"));
      List<Student> list1 = new ArrayList<>();
      list1.addAll(list);

      // Modify the original list and change will reflect in both list
      list.get(0).setName("Zara Vasim");
      System.out.println(list);
      System.out.println(list1);

      // Modify the copied list and change will reflect in both list
      list1.get(0).setName("Zara");
      System.out.println(list);
      System.out.println(list1);
   }
}
class Student {
   private int id;
   private String name;
   public Student(int id, String name) {
      this.id = id;
      this.name = name;
   }
   public int getId() {
      return id;
   }
   public void setId(int id) {
      this.id = id;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   @Override
   public boolean equals(Object obj) {
      if(!(obj instanceof Student)) {
         return false;
      }
      Student student = (Student)obj;
      return this.id == student.getId() && this.name.equals(student.getName());
   }
   @Override
   public String toString() {
      return "[" + this.id + "," + this.name + "]";
   }
}

This will produce the following result −

Output

[[1,Zara Vasim], [2,Mahnaz], [3,Ayan]]
[[1,Zara Vasim], [2,Mahnaz], [3,Ayan]]
[[1,Zara], [2,Mahnaz], [3,Ayan]]
[[1,Zara], [2,Mahnaz], [3,Ayan]]

Updated on: 10-May-2022

522 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements