1

It says The Java ArrayList clone() method makes the shallow copy of an array list. But when I delete the value from the original list it is not reflected in the cloned list.

import java.util.*;  
 public class Test{  
     public static void main(String args[]){  
          ArrayList<String> list=new ArrayList<String>();
          list.add("Mango");    
          list.add("Apple");    
          list.add("Banana");    
          list.add("Grapes");         
          ArrayList<String> list2;    
          list2=(ArrayList)list.clone();
          list.remove(0);
          System.out.println(list); //[Apple, Banana, Grapes]
          System.out.println(list2); //[Mango, Apple, Banana, Grapes] 
    }  
}

When I compile this program it shows

Note: Test.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details
Slaw
  • 37,820
  • 8
  • 53
  • 80
  • 3
    This is as designed. A shallow copy means that all the references to the contained objects are copied, and not the objects themselves. So you have got two lists that can be deleted from individually (not just two references to the same list). – Ole V.V. Jun 05 '21 at 06:19
  • 3
    Check out [What is the difference between a deep copy and a shallow copy?](https://stackoverflow.com/questions/184710/what-is-the-difference-between-a-deep-copy-and-a-shallow-copy). – Slaw Jun 05 '21 at 06:20
  • @OleV.V. A shallow copy of a collection is a copy of the collection structure, not the elements. Internally ,it creates collection object (list2=new ArrayList(list)). am I right? – Shyam Prasanna Jun 05 '21 at 06:54
  • It depends on what you mean by *structure*. The result of `clone()` is the same as the result of `list2=new ArrayList(list)`, you are right. – Ole V.V. Jun 05 '21 at 08:38

0 Answers0