Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the last object get copied multiple times in an ArrayList?

Tags:

java

arraylist

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!

like image 602
Paris Karagiannopoulos Avatar asked Dec 01 '22 00:12

Paris Karagiannopoulos


1 Answers

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.

like image 71
Eran Avatar answered May 18 '23 15:05

Eran