我正在尝试将名为 City 的 class 的对象添加到 ArrayList
中。这是该类的代码
public class City {
public static int x;
public static int y;
City(){
Random rand = new Random();
this.x = rand.nextInt(100)+1;
this.y = rand.nextInt(100)+1;
}
}
这是我的Main类的代码:
public static int N = 10;
public static ArrayList<City> cities = new ArrayList<City>();
public static void main(String[] args) {
for (int i=1; i<N; i++){
cities.add(new City());
}
for (City c : cities)
System.out.print("("+c.x+", "+c.y+")");
}
}
println
的结果始终相同,并且看起来 数组列表 仅在所有元素中存储最后添加的对象。例如,运行程序时我得到的结果是:(52, 93)(52, 93)(52, 93)(52, 93)(52, 93)(52, 93)(52, 93)(52, 93)(52, 93)
为什么我得到了这样的结果?如何解决?
谢谢您的帮助!