为什么最后一个对象得到一个ArrayList多次复制? [英] Why does the last object get copied multiple times in an ArrayList?
问题描述
我想的的类的名为城市的对象添加到的ArrayList
。这是code为类
I am trying to add objects of a class named City to an ArrayList
. This is the code for the class
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;
}
}
这是的code我的主类的
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
的结果总是相同的,它似乎像的数组列表的门店只有最后中的所有元素的加入对象。
The result of println
is always the same and it seems like the array list stores only the last object added in all of its elements.
例如,当我运行程序我得到的结果是:
For example the results I get when I run the program is:
(52, 93)(52, 93)(52, 93)(52, 93)(52, 93)(52, 93)(52, 93)(52, 93)(52, 93)
为什么我得到的结果?我怎样才能得到它固定?
Why do I get that results? How can I it be fixed?
在此先感谢!
推荐答案
您应该改变你的城市
类的成员是非静态的:
You should change the members of your City
class to be non static:
public int x;
public int y;
静态成员在类的所有实例中共享,因此所有的实例将具有相同的值。
static members are shared among all instances of a class, so all the instances would have the same values.
这篇关于为什么最后一个对象得到一个ArrayList多次复制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!