0
class Point
{
    double x;
    double y;

    public String toString()
    {
        return x + " " + y;
    }
}
class Main
{
    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);

        Point points = new Point();
        ArrayList<Object> coordinates = new ArrayList<Object>();

        for (int i = 0; i < 3; i++)
        {
            points.x = input.nextDouble();
            points.y = input.nextDouble();
            coordinates.add(points);
        }

        for (Object i : coordinates)
        {
            System.out.println(i);
        }
    }
}

I want to store 10 x and y coordinates in an arraylist i tried to create a class and store arraylist of objects which have both x and y coordinates i am using a loop because i want to store many points and when i use a loop it stores the last point only ten times how can solve this problem thanks

Dedicated User
  • 97
  • 1
  • 1
  • 11

1 Answers1

3

change your loop to

    for (int i = 0; i < 3; i++)
    {
       Point points = new Point();
        points.x = input.nextDouble();
        points.y = input.nextDouble();
        coordinates.add(points);
    }

You need to create new object and put it into your list, so the list contains references to multiple objects, with different values. Otherwise you are mutating the the same object multiple times and the list contains multiple references to the same object.

Michal
  • 970
  • 7
  • 11