Java ArrayList.clone() Method

 Posted On  | Yashwant Chavan 

In this tutorial you will learn how to make clone object of List using ArrayList.clone() method.

syntax

ArrayList.clone() method returns a shallow copy of this ArrayList instance.

 Object java.util.ArrayList.clone()

Return

Returns a shallow copy of this ArrayList instance.

Java ArrayList.clone() example

Refer below steps

  • Constructs an empty list with an initial capacity using new ArrayList().
  • Add some elements in colors ArrayList using add() method.
  • Make shallow copy of ArrayList using .clone() method, clone() method returns Object, so you need to have to cast to ArrayList.
  • Print the elements of clone copy.
package com.technicalkeeda.app;

import java.util.ArrayList;

public class ArrayListClone {
    public static void main(String[] args) {

        ArrayList <String> colors = new ArrayList <String> ();
        colors.add("Red");
        colors.add("Green");
        colors.add("Blue ");

        ArrayList <String> cloneColors = (ArrayList <String> ) colors.clone();
        cloneColors.add("Pink");

        System.out.println("Colors List Size:- " + colors.size());
        System.out.println("Clone Colors List Size:- " + cloneColors.size());

        System.out.println("\nShallow Copy of ArrayList");
        for (String color: cloneColors) {
            System.out.println("Color:- " + color);
        }

    }
}

Output

Colors List Size:- 3
Clone Colors List Size:- 4

Shallow Copy of ArrayList
Color:- Red
Color:- Green
Color:- Blue 
Color:- Pink


© technicalkeeda.com 2017

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0419 seconds.