Question

i know that ArrayList objects are only passed as reference, and i found a lot of articles here about that topic.

Still, even with cloning the ArrayList to a temporary one nor with copying the Point[] out of it, i can get it working. What am i doing wrong? The target should be to have a separate ArrayList in

// setting class
public ArrayList<Point[]> getAstroidForms(){
    return astroidForms;
}

// class where i want to have a list of Point[] 
// that i can modify without changing the objects in the settings class
for (Point[] foo: settings.getAstroidForms()) {
    Point[] parr = new Point[foo.length];
    System.arraycopy(foo, 0, parr, 0, foo.length);
    forms.add(parr);
}

as written above i also tried the following: Cloning the astroidsForms and returning it in the getAstroidForms method, but again the objects that are modified in the second class seem only to be referenced.

Many thanks for any help provided!

Was it helpful?

Solution

Your list contains array of references to objects of type Point. So, when you create new array you allocate new memory and really create clone. However wehn you call System.arraycopy() (that is just a faster version of ordinary loop you can code youreself) you copy content of each cell of your original array to appropriate cell of your target array, i.e. copy references.

If you want deep clone you have to create copy of each object of Point. You can use either utility method or copy constructor or make Point clonable:

for (Point[] foo: settings.getAstroidForms()) {
    Point[] parr = new Point[foo.length];
    for (int i = 0; i < parr.length; i++) {
        parr[i] = new Point(foo[i]); // I assume here that you implemented correct copy constructor
    }
}    
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top