为什么在ArrayList中最后一个对象会被复制多次?

4

我正在尝试将名为 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)

为什么我得到了这样的结果?如何解决?
谢谢您的帮助!
2个回答

13

你应该将 City 类的成员改为非静态的:

public int x;
public int y;

静态成员在类的所有实例之间共享,因此所有实例都将具有相同的值。


@Thomas 是的,最好将 x 和 y 设为私有,并通过 setter 和 getter 方法访问它们。 - Eran

7
City类中的xy变量被标记为static。一个static成员在class的所有实例之间共享,因此是一个全局变量。您需要对代码进行几个更改:

  1. cityxy变量的声明更改为private int xprivate int y。理想情况下,类的字段不应该是public。详细解释请参见此答案
  2. City类中添加getXgetY方法。
  3. main方法中,使用getXgetY访问xy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接