我正在尝试使用以下代码创建Points平面:
班级环境:
public class Environment {
public ArrayList<Point> plane = new ArrayList<Point>();
public void addToPlane(Point point) {
plane.add(point);
}
public void showplane() {
for(int x=1; x<=2500; x++) {
Point point2 = new Point();
point2 = plane.get(x);
System.out.println("x = "+point2.getX()+"; y = "+point2.getY());
}
}
}
Class EnvironmentTest:
public class EnvironmentTest {
public static void main(String[] args) {
Environment env = new Environment();
Helper help = new Helper();
help.createPlane(env,50,50);
env.showplane();
}
}
班助手:
public class Helper {
public void createPlane(Environment env, int i, int j) {
Point point = new Point();
for(int x=0; x<=i; x++) {
for(int y=0; y<=j; y++) {
point.setLocation(x, y);
System.out.println(x+"+"+y);
env.addToPlane(point);
}
}
}
}
当我运行showplane()时,我在控制台中得到的是
...
50+38
50+39
50+40
50+41
...
现在一切都很好但是当我尝试列出我的积分时我只得到:
x = 50.0; y = 50.0
x = 50.0; y = 50.0
x = 50.0; y = 50.0
x = 50.0; y = 50.0
x = 50.0; y = 50.0
我哪里弄错了?
答案 0 :(得分:3)
//Point point = new Point(); // removed
for(int x=0; x<=i; x++) {
for(int y=0; y<=j; y++) {
Point point = new Point(); // added
point.setLocation(x, y);
System.out.println(x+"+"+y);
env.addToPlane(point);
}
}
您只创建一个Point对象(因此相同的值会一遍又一遍地显示)。您需要在循环中为每个点创建一个新的Point对象。
答案 1 :(得分:1)
您一遍又一遍地使用相同的Point对象,在setLocation()之前创建一个新对象