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());
}
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.
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());
}
this solved problem :)
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 );
Point coord = new Point();
coord.set(x, y);
pointList.add(i , coord);
coord=null;
Log.d("pointList", pointList.toString());
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.