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;
}
}
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 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?
Thanks in advance!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With