将阵列复制到另一个阵列

Sam*_*yan 0 java arrays copy

我试图将一个数组的内容复制到另一个数组而不指向相同的内存,但我不能.

我的代码:

class cPrueba {
    private float fvalor;

    public float getFvalor() {
        return fvalor;
    }

    public void setFvalor(float fvalor) {
        this.fvalor = fvalor;
    }
}

List<cPrueba> tListaPrueba = new ArrayList<cPrueba>();
List<cPrueba> tListaPrueba2 = new ArrayList<cPrueba>();

cPrueba tPrueba = new cPrueba();
tPrueba.setFvalor(50);
tListaPrueba.add(tPrueba);

tListaPrueba2.addAll(tListaPrueba);
tListaPrueba2.get(0).setFvalor(100);

System.out.println(tListaPrueba.get(0).getFvalor());
Run Code Online (Sandbox Code Playgroud)

结果是"100.0"....

仍然指向同一个对象...任何简短的复制方式?(不适用于(..){})

编辑:

class cPrueba implements Cloneable {
    private float fvalor;

    public float getFvalor() {
        return fvalor;
    }

    public void setFvalor(float fvalor) {
        this.fvalor = fvalor;
    }

    public cPrueba clone() {
        return this.clone();
    }
}

List<cPrueba> tListaPrueba = new ArrayList<cPrueba>();
List<cPrueba> tListaPrueba2 = new ArrayList<cPrueba>();

cPrueba tPrueba = new cPrueba();
tPrueba.setFvalor(50);
tListaPrueba.add(tPrueba);

for ( cPrueba cp : tListaPrueba )
    tListaPrueba2.add(cp);

tListaPrueba2.get(0).setFvalor(100);

System.out.println(tListaPrueba.get(0).getFvalor());
Run Code Online (Sandbox Code Playgroud)

仍然得到100 ......

fge*_*fge 5

没有办法" 深度复制"数组,或任何类型Collection(包括List),或者即使Map您的对象本身没有深度复制支持(例如,通过复制构造函数).

所以,对你的问题:

任何简短的复制方式?(不适用于(..){})

答案是不.

当然,如果您的对象是不可变的,那么这不是一个问题.