[英]Copy method in java
我正在尝试将一个列表复制到另一个列表中,我有其他方法,例如删除,当我测试它们时,复制方法似乎正在编辑原始列表。
复制方法如下所示。
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);
}
}
把代码改成这个,还是不行
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
是对原始列表的 head 元素的引用。 它根本不是副本。 然后将其作为参数listcopy
传递给copynode
方法,并且copynode
其中的条目。
实际上,在第 6 行的copynode()
调用中, list.head.next
== listcopy.head.next
(如,两者都指向完全相同的 Node 对象)。这就是问题所在。
如果您尝试连接多个不可变列表,您可以使用静态内部类 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);
输出:[1,2,3,4,5,6]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.