I have issues getting my ArrayList to add properly. When I print the ArrayList after the for loop has finished, the ArrayList is the correct length, but every element is the same (the last Coordinate that was created).
Can someone fix (and explain) the code below?
public class test {
private static ArrayList<Coordinate> mOrigCoords;
private static ArrayList<Coordinate> mNewCoords;
private static int mListSize;
private static int mPixelsX;
public static void main(String[] args)
{
mOrigCoords = new ArrayList<Coordinate>();
mNewCoords = new ArrayList<Coordinate>();
mPixelsX = 480;
int j = 0;
Coordinate newCoord = new Coordinate(0,0);
for(int i = 0; i < 96; i++)
{
j = j + 5;
newCoord.setX(j);
newCoord.setY((int)(Math.random()*300));
mOrigCoords.add(newCoord);
}
mListSize = mOrigCoords.size();
for(int n = 0; n < mListSize; n++)
{
System.out.println("test " + mOrigCoords.get(n).toString());
}
}
}
Thanks in advance for the help!
Instead of
Coordinate newCoord = new Coordinate(0,0);
for(int i = 0; i < 96; i++)
{
j = j + 5;
newCoord.setX(j);
newCoord.setY((int)(Math.random()*300));
mOrigCoords.add(newCoord);
}
you should have
Coordinate newCoord = null;
for(int i = 0; i < 96; i++)
{
newCoord = new Coordinate(0,0);
j = j + 5;
newCoord.setX(j);
newCoord.setY((int)(Math.random()*300));
mOrigCoords.add(newCoord);
}
This way, the arrayList will hold many objects instead of only one. All the elements in your ArrayList are pointing to the same object, that was the cause of trouble.
you have to do like this :
Coordinate newCoord;
for(int i = 0; i < 96; i++)
{
newCoord = new Coordinate(0,0);
...
Because in your case you are setting the same object (newCoord) each time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With