Java 数组列表帮助

Java 数组列表帮助,java,reference,arraylist,Java,Reference,Arraylist,我试图将一个对象添加到数组列表中,但有点困难。我知道我的问题,但不知道如何解决。基本上,问题是我将引用分配给数组列表中的对象x次。这很好,我想要这个。然而,引用总是变为最后添加的内容 这是我的密码: ID ids = new ID("1", "this is a string", "213", "example", "my", "name", "7939","1d", "1"); idarray.add(ids); ids = new ID("2", "this too, is a strin

我试图将一个对象添加到数组列表中,但有点困难。我知道我的问题,但不知道如何解决。基本上,问题是我将引用分配给数组列表中的对象x次。这很好,我想要这个。然而,引用总是变为最后添加的内容

这是我的密码:

ID ids = new ID("1", "this is a string", "213", "example", "my", "name", "7939","1d", "1");
idarray.add(ids);

ids = new ID("2", "this too, is a string", "12314", "example2", "my", "name", "250","1234", "1");
idarray.add(ids);

ids = new ID("3", "Hey look! another string!", "10941", "examplar!", "my", "name", "1341","da34", "0");
idarray.add(ids);

ids = new ID("4", "the final example!", "109231091", "for example", "my", "name", "799","DF1234", "0");
idarray.add(ids);

我的想法是尝试创建一个包含所有这些信息的新“]ID”对象,然后将其存储在一个“ids”arraylist中以供以后访问。问题是我只存储引用,调用时似乎每个存储的引用都指向最后一个in值?

以访问指定的对象

int index = 0;
ids = idarray.get(index);
这样,您就可以检索已添加的对象

您不能将所有引用存储在一个变量中,因为您使用数组或集合,这就是为什么会更改为最后一个值,因为您每次调用时都会分配新的引用:

ids = new ID("2", "this too, is a string", "12314", "example2", "my", "name", "250","1234", "1");
ids = new ID("3", "Hey look! another string!", "10941", "examplar!", "my", "name", "1341","da34", "0");

现在ids变量指向您分配的最后一个引用。

对不起,我仍然不知道问题出在哪里。你能发布给你不想要的结果的代码吗?你发布的代码似乎是正确的。考虑张贴一些你正在得到的输出,指示某个东西正在失效。你的代码看起来是正确的。您能否发布显示“每个存储的引用都指向最后一个in值”的代码?您的
ID
类中的字段是否是静态的?如果您执行类似于
class ID{static String ID;ID(String theId,…{ID=theId;}}}
的操作,那么对
ID
构造函数的每次调用都将结束上一次调用所做的工作。为什么要将数字作为字符串存储在ID构造函数中??