将元素添加到ArrayList

时间:2017-10-05 22:20:53

标签: java arraylist lwjgl

我试着写一个应该创建圆柱体的类。但是当我尝试绘制我的ArrayList时,有180个具有相同值的对象。当我尝试将Quad添加到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);
}
}

1 个答案:

答案 0 :(得分:0)

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;
}

您已经创建了CordN变量static,因此每个字段只有1个值,在类的所有实例之间共享。因此,每次创建类的新实例时,都会覆盖先前的值。

删除static修饰符。

另外,请注意,制作成员变量final是一种很好的做法,除非您绝对不需要它们。这似乎不是这种情况,因此请将它们final - 并且这会自动捕获您的问题,因为您无法在构造函数中重新分配static final字段。