嗨,我正在尝试将一个对象添加到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).
非常感谢你的回复.
|   归档时间:  |  
           
  |  
        
|   查看次数:  |  
           7316 次  |  
        
|   最近记录:  |