how to clone a Vector in codenameone

Viewed 17

I need a clean copy of a Vector not a reference.

In Swing I use Vector.clone(); (Not Allowed in codenmeone complains its protected.)

In Codenameone I tried Vector someName = new Vector((Vector)anotherVector)

someName becomes a referance as what ever changes are made to anotherVector, someName inherits those changes.

Thoughts?

Best Regards

1 Answers

The new vector approach works but it isn't a deep copy of the elements within. Unfortunately you can't do a deep copy since clone() requires reflection which we don't have. Unfortunately there's no easy answer. You would need to literally go over every element and create a copy of that element since we can't generically duplicate it.

This can be relatively simple, assuming a vector of MyObject which has a constructor that accepts an existing instance then something like this will work:

Vector<MyObject> newVector = new Vector<>();
for(MyObject obj : oldVector) {
    newVector.add(new MyObject(obj));
}
Related