无法在ArrayList中添加对象?

JLT*_*hiu 1 java optimization

嗨,我正在尝试将一个对象添加到Arraylist中,我正在使用Java.但它并不像我预期的那样有效.

假设我们有一个类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); 
}
Run Code Online (Sandbox Code Playgroud)

上面的一个正常工作.但我希望加快我的代码,所以我尝试只新的一个obejct,代码变成:

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); 
}
Run Code Online (Sandbox Code Playgroud)

但是,在这种情况下,我的结果将变为空.我想我确实改变了对象中的内容s,但我不知道为什么它在这期间不起作用result.add(s).

非常感谢你的回复.

Tim*_*tan 5

您的s变量始终引用同一个对象.看起来你要添加相同的对象10次,在for循环结束时,它的字符串将等于"9"并且其int等于9.