简体   繁体   中英

Copy method in java

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;
}

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.

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM