Copy method in java

156 Views Asked by At

I am trying to copy a list into another list, I have other methods such as remove and when I am testing them the copy method seems to be editing the original list.

The copy method is shown hereunder.

public ImmutableList<T> copy(ImmutableLinkedList<T> list) {
    Node n = list.head;
    ImmutableLinkedList<T> listcopy = new ImmutableLinkedList<T>();
    listcopy.head = list.head;

   copynode(list.head.next, listcopy.head.next);
   return listcopy;
}

private Node copynode(Node list, Node listcopy){
    if(list == null){
        return listcopy;
    } else{
        listcopy.data = list.data;
        listcopy.next = list.next;
     return copynode(list.next, listcopy.next);
    }
}

Altered the code to this, but still not working

public void copy(ImmutableListImplement<T> list) {


  ImmutableListImplement<T> listcopy = new ImmutableListImplement<T>();

    this.head = copynode(list.head, listcopy.head);


}

private Node copynode(Node list, Node listcopy){


    if(list == null){
        return listcopy;
    } else{

        listcopy = new Node();
        listcopy.data = list.data;
        listcopy.next = list.next;


        copynode(list.next, listcopy.next);
    }
    return listcopy;
}
2

There are 2 best solutions below

0
On

If you are trying to concatenate multiple immutable lists you can use the static inner class ImmutableList.Builder.

        List<String> list = new ArrayList<>( 
            Arrays.asList("4", "5", "6"));

        ImmutableList<String> iList = ImmutableList.<String>builder() 
                                        .add("1", "2", "3")
                                        .addAll(list) 
                                        .build(); 

        System.out.println(iList); 

Output: [1,2,3,4,5,6]

2
On

listcopy.head is a reference to the original list's head element. It is not a copy at all. Then you pass this into the copynode method as parameter listcopy, and copynode messes with the entries therein.

Effectively, list.head.next == listcopy.head.next (as in, both point to the exact same Node object) in your copynode() call on line 6. That's the problem here.