Why is the last object copied several times in an ArrayList?

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!

+4
source share
2 answers

Variables xand yin Citymarked as static. The member staticis common to all instances of a classand, therefore, is a global variable. You need to make a couple of changes to the code:

  • x y private int x private int y. public. . .
  • getX getY City.
  • main x y getX getY.
+7

City :

public int x;
public int y;

, .

+13

All Articles