Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In an array list, new variable gets added and as well as replaces the existing values with new one

In an array list, when new variables are added using

 pointList.add(i , coord); 

the new variable gets added and as well as replaces the existing values with new one. how to stop these replacing variables ?

for(int i=0;i<coordinateArray.length();i++)
        {
            brokenArray= coordinateArray.getJSONObject(i);  
            x=brokenArray.getInt("x");
            y=brokenArray.getInt("y");

            Log.d("x", " "+i+ " "+x );
            Log.d("y", " "+i+ " "+y );

            coord.set(x, y);
            pointList.add(i , coord);

            Log.d("pointList", pointList.toString());
        }
like image 359
jeet.chanchawat Avatar asked Jan 27 '26 10:01

jeet.chanchawat


2 Answers

Based on the code you've provided, you're using coord.set(x, y) on the same object every time. Adding an object to a List does not make a copy of it.

Java passes references by value, not objects by value; when you call pointList.add(i, coord), you are adding a reference to the coord object to the list, not a new copy of the coord object.

Instead, you must create a new Point or Coordinates or whatever object each time through the loop. You cannot reuse the coord object the way you're doing it here.

like image 134
Louis Wasserman Avatar answered Jan 28 '26 23:01

Louis Wasserman


This is the bug.

 coord.set(x, y);

You are setting the value in the loop to the same object.

Create the coord object inside the loop and add it.

for(int i=0;i<coordinateArray.length();i++)
    {
        brokenArray= coordinateArray.getJSONObject(i);  
        x=brokenArray.getInt("x");
        y=brokenArray.getInt("y");

        Log.d("x", " "+i+ " "+x );
        Log.d("y", " "+i+ " "+y );
        Coordinate coord = new Coordinate ();
        coord.set(x, y);

        pointList.add(i , coord);

        Log.d("pointList", pointList.toString());
    }
like image 27
Ramesh PVK Avatar answered Jan 28 '26 23:01

Ramesh PVK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!