Initializing a collection from another one
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   amit_mendelson
Posted On:   Tuesday, August 15, 2006 01:58 AM

Hi, I'm trying the following code: class Amit { public Amit(int i) { this.value = i; } public int value = 100; }; public void testAmit() { List amits = new ArrayList (); Amit amit = new Amit(5); amits.add(amit); List moreAmits = new ArrayList (amits); moreAmits.iterator().next().value = 10; assertEquals(5,amit.value); } Result: the assertion failed (amit.value is 10, not 5). How should I initialize the new list ("moreAmits") so it will create new instances of the objects i   More>>

Hi,

I'm trying the following code:


class Amit {


public Amit(int i) {


this.value = i;


}


public int value = 100;


};


public void testAmit() {


List amits = new ArrayList ();


Amit amit = new Amit(5);
amits.add(amit);


List moreAmits = new ArrayList (amits);


moreAmits.iterator().next().value = 10;


assertEquals(5,amit.value);

}


Result: the assertion failed (amit.value is 10, not 5).
How should I initialize the new list ("moreAmits") so it will create new instances of the objects in the previous list, and won't reference the same items?

   <<Less

Re: Initializing a collection from another one

Posted By:   Robert_Lybarger  
Posted On:   Tuesday, August 15, 2006 11:52 PM

I really thought it would be easier than this. It is somewhat late for me after a long day, so I probably just went down a blind alley, but this is *a* solution, though I really don't imagine its the *best* one. It sounds like you are looking for the "public Object clone()" method. Implement this in your Amit class to return a new Amit instance with the correct values copied over. Then, when creating "newAmits", just create an empty ArrayList, then loop through the original version, calling "clone()" on each one in turn and adding the result to your "newAmits" member. Here's how it looks, with your 'assertEquals' removed:

import java.util.ArrayList;
import java.util.List;

class Cloning {
public static void main(String[] args) {
new Cloning();
}
public Cloning() {
List amits = new ArrayList();
Amit amit = new Amit(5); amits.add(amit);
List moreAmits = new ArrayList();
for(Amit a : amits) {
moreAmits.add( (Amit)(a.clone()));
}
moreAmits.iterator().next().value = 10;
System.out.println("original amit value is: "+amit.value);
}
}

...and...



public class Amit implements Cloneable {
public Amit(int i) {
this.value = i;
}
public int value = 100;
public Object clone() {
Amit newAmit = new Amit(this.value);
return newAmit;
}
}

Pity I can't find (there doesn't seem to be?) a "copyAllElements" method in the standard collections classes to help abstract this... though you'd still need to write an implementation for your "clone" either way.

About | Sitemap | Contact