Search code examples
javagraphicsjava-3d

How to join 2 Point3f arrays together?


How can I join 2 Point3f arrays together?

I have tried this but it returns null pointer exception :(

private Point3f[] combineRings(Point3f[] a, Point3f[] b){
    int size = a.length+b.length;
    System.out.println("Size = "+size);
    Point3f[] c = new Point3f[size];
    for(int i = 0, j = 0; i < size; i+=2, j++){

        c[i].x = a[j].getX();
        c[i].y = a[j].getY();
        c[i].z = a[j].getZ();

        c[i+1].x = b[j].getX();
        c[i+1].y = b[j].getY();
        c[i+1].z = b[j].getZ();

        // Debugging
        System.out.println(i+"\t"+j+"\t"+c[i]+"\t"+a[j]+"\t"+c[i++]+"\t"+b[j]);
    }
    return c;
}

Thanks.


Solution

  • An array is empty until you put objects into it. Your code assumes that you can assign to c[i].x immediately, but as there's no object in c[i], you get a NullPointerException.

    I don't know if you want to copy the objects in the arrays into new objects, or if you just want to copy the references so both arrays point to the same objects. The second one is easy:

    System.arraycopy(a, 0, c, 0, a.length);
    System.arraycopy(b, 0, c, a.length, b.length);
    

    If it's the first one, it'd be much simpler to use the Point3f copy constructor:

    for (int i=0; i<a.length; ++i)
        c[i] = new Point3f(a[i]);
    
    for (int i=0; i<b.length; ++i)
        c[i+a.length] = new Point3f(b[i]);