SamYan
SamYan

Reputation: 1571

Copying Array to another Array

im trying to copy the contents of one array to another without pointing to the same memory, but i cant.

My Code:

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());

The result is "100.0" ....

Still pointing to the same object... Any short way to copy ? (without for(..){})

EDIT:

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());

Still get 100...

Upvotes: 0

Views: 166

Answers (3)

user1447460
user1447460

Reputation:

Like dystroy said, you'll need to pass through the loop and clone all of the objects, like this:

List<cPrueba> newList = new ArrayList<cPrueba>();
for ( cPrueba cp : oldList )
    newList.add(cp.clone());

And that's assuming your object implements Cloneable, or at least has a method called clone.

So no, there is no short way (unless you write your own static method), but it is possible.

EDIT You need your clone method to return a new cPrueba:

public cPrueba clone() {
    cPrueba c = new cPrueba();
    c.setFvalor(this.getFvalor());
    return c;
}

Also, make sure you call cp.clone() in your for loop; don't just pass cp to the add method. e.g., change

tListaPrueba2.add(cp);

to

tListaPrueba2.add(cp.clone());

Upvotes: 1

Vegard
Vegard

Reputation: 1942

vanilla Java can't do this for you.

but by adding some spice you can get it done with the Dozer framework:

http://dozer.sourceforge.net/

Upvotes: 0

fge
fge

Reputation: 121860

There is no way to "deepcopy" an array, or any kind of Collection (which includes List) or even Map if your object itself does not have deep copy support (for instance, via a copy constructor).

So, to your question:

Any short way to copy ? (without for(..){})

the answer is no.

Of course, if your objects are immutable, this is not a concern.

Upvotes: 5

Related Questions