Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

problem with ArrayList in Java

Tags:

java

arraylist

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!

like image 871
developer Avatar asked Dec 01 '25 08:12

developer


2 Answers

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.

like image 58
Lajos Arpad Avatar answered Dec 03 '25 23:12

Lajos Arpad


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.

like image 22
Michaël Avatar answered Dec 03 '25 22:12

Michaël



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!