Search code examples
javaarraylistlwjgl

Adding Elements to an ArrayList


I tried to write a class wich should create a cylinder. But when I try to draw my ArrayList there are 180 Objects with the same Value in it. I don't understand what's wrong in there when I try to add the Quads to my ArrayList.

public class Planet {
    public static ArrayList<Quad> createRing(int x, int y, int z, int radius) {
        ArrayList<Quad> quads = new ArrayList<Quad>();
        for (int i = 0; i < 360; i++) {
            float x1 = (float) (Math.sin(Math.toRadians(i)) * radius);
            float y1 = (float) (Math.cos(Math.toRadians(i)) * radius);
            i++;
            float x2 = (float) (Math.sin(Math.toRadians(i)) * radius);
            float y2 = (float) (Math.cos(Math.toRadians(i)) * radius);

            quads.add(new Quad(new Vector3f(x1, y1, 4), new Vector3f(x2, y2, 4), new Vector3f(x2, y2, 0),
                    new Vector3f(x1, y1, 0)));
        }
        return quads;
    }
}

----QUAD.java

import org.lwjgl.opengl.GL11;
import org.lwjgl.util.vector.Vector3f;

public class Quad {
//have to be non-static
static Vector3f Cord1; 
static Vector3f Cord2;
static Vector3f Cord3;
static Vector3f Cord4;
//have to be non-static
public Quad(Vector3f cord1,Vector3f cord2,Vector3f cord3,Vector3f cord4) {
Cord1 = cord1;
Cord2 = cord2;
Cord3 = cord3;
Cord4 = cord4;
}
public void draw() {
//GL11.glBegin(GL11.GL_QUADS);
GL11.glColor3f(1, 0, 0);
GL11.glVertex3f(Cord1.x, Cord1.y, Cord1.z);
GL11.glVertex3f(Cord2.x, Cord2.y, Cord2.z);
GL11.glVertex3f(Cord3.x, Cord3.y, Cord3.z);
GL11.glVertex3f(Cord4.x, Cord4.y, Cord4.z);
}
public void out() {

System.out.println(Cord1.x+" "+ Cord1.y+" "+ Cord1.z);
System.out.println(Cord2.x+" "+ Cord2.y+" "+ Cord2.z);
System.out.println(Cord3.x+" "+ Cord3.y+" "+ Cord3.z);
System.out.println(Cord4.x+" "+ Cord4.y+" "+ Cord4.z);
}
}

Solution

  • public class Quad {
    static Vector3f Cord1;
    static Vector3f Cord2;
    static Vector3f Cord3;
    static Vector3f Cord4;
    public Quad(Vector3f cord1,Vector3f cord2,Vector3f cord3,Vector3f cord4) {
    Cord1 = cord1;
    Cord2 = cord2;
    Cord3 = cord3;
    Cord4 = cord4;
    }
    

    You have made the CordN variables static, so each field has just 1 value, shared between all instances of the class. As such, each time you create a new instance of the class, the previous values are overwritten.

    Remove the static modifier.


    Also, note that it's good practice to make member variables final unless you absolutely need them not to be. That does not appear to be the case here, so make them final - and this would have caught your issue automatically, because you wouldn't be able to reassign a static final field in the constructor.