您好我正在尝试将对象添加到 Arraylist 中,我正在使用 Java。但它没有按我的预期工作。
假设我们有一个 class Sentence
,所以代码看起来像
ArrayList<Sentence> result = new ArrayList<Sentence>();
for (int i =0; i<10;i++)
{
Sentence s = new Sentence(i.toString(),i);
//there is a string and an int in this Sentence object need to be set
result.add(s);
}
以上工作正常。但我希望加快我的代码,所以我尝试只新建一个对象,代码变为:
ArrayList<Sentence> result = new ArrayList<Sentence>();
Sentence s = new Sentence(" ",0);
for (int i =0; i<10;i++)
{
s.setString(i.toString());
s.setInt(i);
result.add(s);
}
但是,在这种情况下,我的结果将变为空。我想我确实更改了对象中的内容s
,但我不知道为什么它在result.add(s)
.
非常感谢您的回复。