ArrayList Copy Cloning Java

ArrayList Copy Cloning Java


Before going through this program ArrayList copy Cloning, it is advised to read first ArrayList Introduction where all the methods, class signature, constructors and history are given.

4 programs are given on Arraylist.

  1. ArrayList Methods: In this program, the basic operations on array list are performed like addition, checking the list is empty or not, removing the elements, knowing the index number of an element etc.
  2. ArrayList Iterators: In this example, different styles of retrieving and printing the array list elements are described.
  3. ArrayList Operations: In this program, operations like reversing, sorting, searching, swapping, shuffling, filling, knowing maximum and minimum values are performed. Finally, an array of array lists is created and the elements are printed.
  4. ArrayList Special: In this program, operations like converting array list to array, array list to string, copying elements of one array into another, converting array to array list and finally cloning of an array list are performed.

This is the last program of the above four – ArrayList Special.

Example on ArrayList copy Cloning

Output screenshot of ArrayList copy Cloning

A generics ArrayList object al1 is created that accepts only integer values. With add() method three elements are added.

All the elements of al1 are converted into an array object numbers with toArray() method, inherited from Collection interface (and overridden by List interface). Using enhanced for loop all the elements are printed. Remember, toArray() method returns an object array of Object.

Java allows many operations on data structures. A data structure class can be converted into a string so that a data structure can be used in string form, as required to place in a text field. The method used is toString() inherited from Object class.

Another generic object al2 is created and copied all the elements of al1 into it with the static method copy() of Collections class. It is like addAll() method of Collection interface (overridden by List interface).

Any data structure can be cloned with clone() method of Object class. Cloning is more elaborately discussed in Cloning – Duplicating an Object – Marker Interface.

An Integer array object num is created with three Integer elements. The array num is converted into List by passing it to asList() method. Like this an array can be converted to a collections class, and also as did earlier, collections class can be converted to array using toArray() method. Finally, List is converted into ArrayList by passing List object al4 to ArrayList constructor.

One thought on “ArrayList Copy Cloning Java

Leave a Reply

Your email address will not be published. Required fields are marked *