ArrayList.Clone() Method is used to create a shallow copy of the specified ArrayList. A shallow copy of a collection copies only the elements of the collection irrespective of reference types or value types. But it does not copy the objects that the references refer to. The references in the new collection point to the same objects that the references in the original collection point to.
Syntax:
public virtual object Clone ();
Below programs illustrate the use of above-discussed method:
Example 1:
using System;
using System.Collections;
public class GFG {
public static void Main(String[] args)
{
ArrayList list = new ArrayList();
list.Add( "Geeks" );
list.Add( "for" );
list.Add( "Geeks" );
list.Add( "10" );
list.Add( "20" );
Console.WriteLine( "Elements of Original ArrayList: \n" );
foreach ( string str in list)
{
Console.WriteLine(str);
}
ArrayList sec_list = new ArrayList();
sec_list = (ArrayList)list.Clone();
Console.WriteLine( "\nElements of Cloned ArrayList: \n" );
foreach ( string str1 in sec_list)
{
Console.WriteLine(str1);
}
}
}
|
Output:
Elements of Original ArrayList:
Geeks
for
Geeks
10
20
Elements of Cloned ArrayList:
Geeks
for
Geeks
10
20
Example 2:
using System;
using System.Collections;
public class GFG {
public static void Main(String[] args)
{
ArrayList list = new ArrayList();
list.Add(10);
list.Add(20);
list.Add(30);
list.Add(40);
list.Add(50);
Console.WriteLine( "Elements of Original ArrayList: \n" );
Result(list);
ArrayList sec_list = (ArrayList)list.Clone();
Console.WriteLine( "\nElements of Cloned ArrayList: \n" );
Result(sec_list);
list.Add(60);
Console.WriteLine( "\nAfter Adding, Original ArrayList: \n" );
Result(list);
Console.WriteLine( "\nAfter Adding, Cloned ArrayList: \n" );
Result(sec_list);
Console.WriteLine( "\nReference Equals: {0}" ,
Object.ReferenceEquals(list, sec_list));
}
public static void Result(ArrayList ar)
{
foreach ( int i in ar)
Console.WriteLine(i);
}
}
|
Output:
Elements of Original ArrayList:
10
20
30
40
50
Elements of Cloned ArrayList:
10
20
30
40
50
After Adding, Original ArrayList:
10
20
30
40
50
60
After Adding, Cloned ArrayList:
10
20
30
40
50
Reference Equals: False
Reference:
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
07 Feb, 2019
Like Article
Save Article