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

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

问题描述

我在正确添加 ArrayList 时遇到问题.当我在 for 循环完成后打印 ArrayList 时,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());
    }

}
}

预先感谢您的帮助!

推荐答案

代替

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天全站免登陆