share

Sunday, 17 May 2015

How To make Shallow Copy Or Clone a LinkedList


import java.util.LinkedList;

public class CloneOfLinkedList {

    public static void main(String[] args) {
       
        LinkedList<String> linkedList = new LinkedList<String>();
       
        linkedList.add("Mumbai");
        linkedList.add("Delhi");
        linkedList.add("Noida");
        linkedList.add("Gao");
        linkedList.add("Patna");
       
        // print linkedlist
       
        for (String str : linkedList) {
            System.out.println("Element is = "+str);
        }
       
        //Returns:a shallow copy of this LinkedList instance
       
        LinkedList<String> mylist = (LinkedList<String>) linkedList.clone();
       
        System.out.println("copy list is ");
        for (String str : mylist) {
            System.out.println("Element is = "+str);
        }
       
    }
   
}

Output:

Element is = Mumbai

Element is = Delhi

Element is = Noida

Element is = Gao

Element is = Patna

copy list is

Element is = Mumbai

Element is = Delhi

Element is = Noida

Element is = Gao

Element is = Patna




No comments:

Post a Comment