views:

330

answers:

3

How would I deep copy a vector in J2ME / BlackBerry?

+2  A: 

You will need to copy the content of your Vector with a loop.

Enumeration e = projects.elements();
while (e.hasMoreElements()) {
    this.projects.addElement((Project) e.nextElement());
}

Need more information see The Java Forum page 2 reply 18, the answer is there.

Michael B.
That does a shallow copy of each of the elements.
DanG
@DanG it's the best you can get in J2ME, Have you even bother read the Vector Docs ? http://en.wikipedia.org/wiki/Object_copy#Deep_vs._Shallow_vs._Lazy_copy if I read correctly the code I have given is a deep copy, since the two vector are independant.
Michael B.
+5  A: 

Unfortunately, there is no reliable way to do a deep copy on a Vector of objects.

Just a quick review of what I believe a "deep copy" is: A deep copy is a copy where not only are the contents of a collection (vector, in this case) copied, but the objects contained in the Vector are copied independently. In other words: If vector V contains A, and a copy (V') of V is made, a copy of A (A') in V' is unaffected by any changes to A and vice versa.

Typically, this would be implemented by "cloning" an object. Unfortunately, if you have no control over the objects in the Vector, you have no reasonable way of cloning them, especially since JavaME does not possess a Cloneable interface (as far as I could find).

Of course, if you do control the objects, you might make your own Cloneable interface that specifies a clone() method that returns a completely independent copy of the object. Then, you must ensure that your special cloning Vector only accepts objects that implement that interface. From there, it's pretty easy (code-wise) for you to make a Vector that can clone itself.

Eric
Alas, that was what I feared. Thanks.
DanG
I could implement a clonable interface, but it wouldn't be nearly as fast as something native to J2ME.
DanG
A: 

Since you tagged this as BlackBerry and not just J2ME it should be mentioned that there is a CloneableVector class that is part of the BlackBerry APIs. If you are trying to stick to strict J2ME this will be of little use. However, if you are just targeting BlackBerry, then it meets your needs.

net.rim.device.api.util.CloneableVector documentation

Fostah
This is version 5.0 only. There are not so much device on 5.0 right now.
Michael B.
That's not true, it's in at least 4.6 and I don't feel like looking further back to check when it first showed up. I just happened to point to the 5.0 doc.
Fostah
I work in 4.3...
DanG
I take it back, its in 4.3. I'll report back soon.
DanG
Well, clone vector works, but it only does a shallow copy.
DanG