1

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.

JayKay
  • 183
  • 1
  • 3
  • 14

2 Answers2

2

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.

Community
  • 1
  • 1
Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
  • 1
    To add to that, copy constructors are where it's at. `Point3d[] newarray = new Point3d[original.length]; for(int i=0, last=newarray.length; i – Mike 'Pomax' Kamermans Aug 01 '14 at 05:44
  • I would use a simple for-loop, but sometimes I have over 100,000 points and I know that for larger arrays, deep-copies are better. Otherwise, I would totally do that. – JayKay Aug 01 '14 at 05:47
  • 1
    @ElliottFrisch nope. [Arrays.copyOf()](http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#copyOf(T[],%20int)) creates a shallow copy. – Nir Alfasi Aug 01 '14 at 05:51
1

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

Community
  • 1
  • 1
Akalanka
  • 310
  • 5
  • 12
  • Oh, I thought clone() would copy _all_ types of values into another variable, not just primitives. Thank You. – JayKay Aug 01 '14 at 05:51