简体   繁体   English

在java中制作深层副本

[英]make deep copy in java

Given the following codes: 鉴于以下代码:

ArrayList<String> original = new ArrayList<String>();
    original.add("one");
    original.add("two");
    original.add("three");

    Cache ch = new Cache();
    ch.store(original);

    original.remove(0);
    original.remove(0);
    System.out.println("modified list is"+original);
    System.out.println("cache list is"+ch.getCache());

and a Cache class: 和一个Cache类:

public class Cache {
private ArrayList<String> clone = new ArrayList<String>();

public void store(ArrayList<String> original){
    this.clone = original;
}

public ArrayList<String> getCache(){
    return this.clone;
}

}

And the output is : 输出是:

modified list is[three]
cache list is[three]

Actually, I want to use the cache to store the original list contains"one, two ,three". 实际上,我想使用缓存来存储包含“一,二,三”的原始列表。 When it stores that list, and a remove is implemented with the 'original' list, it does not affect the one stored in the cache, means it still contains "one,two,three". 当它存储该列表,并且使用“原始”列表实现删除时,它不会影响存储在缓存中的那个,意味着它仍然包含“一,二,三”。 So how to do it? 那怎么办呢?

You are storing only the reference to the list, so the result you have is expected! 您只存储列表的引用,因此您的结果是预期的!

Instead, make a copy when you build: 相反,在构建时制作副本:

public void store(ArrayList<String> original){
    clone = new ArrayList<String>(original);
}

Here IMHO, clone is actually referring to original therefore any changes that you make to original will reflect in clone object. 在这里恕我直言,克隆实际上指的是原始,因此您对原始所做的任何更改都将反映在克隆对象中。 In order to preserve the values in the original ArrayList in clone, one way is copy the contents of original via some logic instead of clone = original; 为了保留克隆中原始ArrayList中的值,一种方法是通过某种逻辑而不是clone = original复制原始内容; // (which is referencing ). //(正在引用)。

In Cache you're declaring and initialising a new array list and then replacing it with the reference of original. Cache您将声明并初始化一个新的数组列表,然后将其替换为原始引用。 Do this: 做这个:

public void store(ArrayList<String> original)
    for(String element:original) {
        this.clone.add(element);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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