在Java中的ArrayList问题 [英] problem with ArrayList in Java

查看:113
本文介绍了在Java中的ArrayList问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须让我的ArrayList正确添加的问题。当我打印该ArrayList for循环完成后,该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).

有人能解决(解释)低于code?

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!

推荐答案

而不是

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);
    }

你应该有

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);
}

此方式,该ArrayList将持有许多对象,而不是仅一个。在ArrayList中所有的元素都指向同一个对象,这是麻烦的原因。

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.

这篇关于在Java中的ArrayList问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆