I am trying to add class objects named City to 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;
}
}
And this is the code of my main class
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+")");
}
}
The result is printlnalways the same, and it seems that the list of arrays stores only the last object added in all its elements.
For example, the results that I get when I start the program:
(52, 93)(52, 93)(52, 93)(52, 93)(52, 93)(52, 93)(52, 93)(52, 93)(52, 93)
Why am I getting these results? How can i fix this?
Thanks in advance!
source
share