JayKay
JayKay

Reputation: 183

Strange array copying error

I am writing a Java3D program that draws a 3D graph. I hold the points of the graph in an array and pass it into a createMesh() and createGraph() function. Here is how I get the points of the graph:

    double x=xmin;
    Point3d[] vertices = new Point3d[graph.length*graph[0].length];
    for(int i=0, index=0; i<graph.length; i++, x+=((xmax-xmin)/graph.length))
    {
        double y = ymin;
        for(int j=0; j<graph[i].length; j++, y+=((ymax-ymin)/graph[i].length), index++)
        {
            double z = Math.sin(Math.pow(x, 2)+Math.pow(y, 2))/(Math.pow(x, 2)+Math.pow(y, 2));
            Point3d point = new Point3d(x, z, y);
            if(z>zmax)
                zmax = z;
            if(z<zmin)
                zmin = z;
            vertices[index] = new Point3d(x, z, y);
        }
    }

In the createGraph() method, I need to set the y-values of the points to 0. To keep the original vertices array unchanged, I copy the array passed to the createGraph() method like this:

private Shape3D createGraph(Point3d[] tempA)
{
    Point3d[] vertices = (Point3d[])tempA.clone();
    ...
}

In the createMesh() method, I don't change the values of the vertices array, so I don't copy it. My program first calls createGraph() and copies the array and then calls createMesh() and reads the original array. The problem is that when I make the mesh using the points in the original vertices array, the y-values of the original array are somehow also 0. I could just call createMesh() first, but I still want to figure out whats going on with my program.

Upvotes: 1

Views: 60

Answers (2)

Akalanka
Akalanka

Reputation: 310

Java Object.clone() will pass a reference to the original object if the Object is not a primitive type. You need to to a deep copy.

Following articles will help you.

A guide to object cloning in java

how-do-you-make-a-deep-copy-of-an-object-in-java

Upvotes: 1

Nir Alfasi
Nir Alfasi

Reputation: 53535

First, it is not recommended to use clone() in Java since clone is broken.

Second, by using clone - you're cloning the array - not the items in the array. For more information in regards read about deep vs. shallow copy.

Upvotes: 2

Related Questions